1//===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the PPCISelLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "PPCISelLowering.h"
14#include "MCTargetDesc/PPCPredicates.h"
15#include "PPC.h"
16#include "PPCCCState.h"
17#include "PPCCallingConv.h"
18#include "PPCFrameLowering.h"
19#include "PPCInstrInfo.h"
20#include "PPCMachineFunctionInfo.h"
21#include "PPCPerfectShuffle.h"
22#include "PPCRegisterInfo.h"
23#include "PPCSubtarget.h"
24#include "PPCTargetMachine.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/None.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/ADT/StringSwitch.h"
37#include "llvm/CodeGen/CallingConvLower.h"
38#include "llvm/CodeGen/ISDOpcodes.h"
39#include "llvm/CodeGen/MachineBasicBlock.h"
40#include "llvm/CodeGen/MachineFrameInfo.h"
41#include "llvm/CodeGen/MachineFunction.h"
42#include "llvm/CodeGen/MachineInstr.h"
43#include "llvm/CodeGen/MachineInstrBuilder.h"
44#include "llvm/CodeGen/MachineJumpTableInfo.h"
45#include "llvm/CodeGen/MachineLoopInfo.h"
46#include "llvm/CodeGen/MachineMemOperand.h"
47#include "llvm/CodeGen/MachineModuleInfo.h"
48#include "llvm/CodeGen/MachineOperand.h"
49#include "llvm/CodeGen/MachineRegisterInfo.h"
50#include "llvm/CodeGen/RuntimeLibcalls.h"
51#include "llvm/CodeGen/SelectionDAG.h"
52#include "llvm/CodeGen/SelectionDAGNodes.h"
53#include "llvm/CodeGen/TargetInstrInfo.h"
54#include "llvm/CodeGen/TargetLowering.h"
55#include "llvm/CodeGen/TargetRegisterInfo.h"
56#include "llvm/CodeGen/ValueTypes.h"
57#include "llvm/IR/CallSite.h"
58#include "llvm/IR/CallingConv.h"
59#include "llvm/IR/Constant.h"
60#include "llvm/IR/Constants.h"
61#include "llvm/IR/DataLayout.h"
62#include "llvm/IR/DebugLoc.h"
63#include "llvm/IR/DerivedTypes.h"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/GlobalValue.h"
66#include "llvm/IR/IRBuilder.h"
67#include "llvm/IR/Instructions.h"
68#include "llvm/IR/Intrinsics.h"
69#include "llvm/IR/Module.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/Value.h"
73#include "llvm/MC/MCContext.h"
74#include "llvm/MC/MCExpr.h"
75#include "llvm/MC/MCRegisterInfo.h"
76#include "llvm/MC/MCSymbolXCOFF.h"
77#include "llvm/Support/AtomicOrdering.h"
78#include "llvm/Support/BranchProbability.h"
79#include "llvm/Support/Casting.h"
80#include "llvm/Support/CodeGen.h"
81#include "llvm/Support/CommandLine.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/Debug.h"
84#include "llvm/Support/ErrorHandling.h"
85#include "llvm/Support/Format.h"
86#include "llvm/Support/KnownBits.h"
87#include "llvm/Support/MachineValueType.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/raw_ostream.h"
90#include "llvm/Target/TargetMachine.h"
91#include "llvm/Target/TargetOptions.h"
92#include <algorithm>
93#include <cassert>
94#include <cstdint>
95#include <iterator>
96#include <list>
97#include <utility>
98#include <vector>
99
100using namespace llvm;
101
102#define DEBUG_TYPE "ppc-lowering"
103
104static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
105cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
106
107static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
108cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
109
110static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
111cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
112
113static cl::opt<bool> DisableSCO("disable-ppc-sco",
114cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
115
116static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
117cl::desc("enable quad precision float support on ppc"), cl::Hidden);
118
119STATISTIC(NumTailCalls, "Number of tail calls");
120STATISTIC(NumSiblingCalls, "Number of sibling calls");
121
122static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
123
124static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
125
126// FIXME: Remove this once the bug has been fixed!
127extern cl::opt<bool> ANDIGlueBug;
128
129PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
130 const PPCSubtarget &STI)
131 : TargetLowering(TM), Subtarget(STI) {
132 // Use _setjmp/_longjmp instead of setjmp/longjmp.
133 setUseUnderscoreSetJmp(true);
134 setUseUnderscoreLongJmp(true);
135
136 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
137 // arguments are at least 4/8 bytes aligned.
138 bool isPPC64 = Subtarget.isPPC64();
139 setMinStackArgumentAlignment(isPPC64 ? 8:4);
140
141 // Set up the register classes.
142 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
143 if (!useSoftFloat()) {
144 if (hasSPE()) {
145 addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass);
146 addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
147 } else {
148 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
149 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
150 }
151 }
152
153 // Match BITREVERSE to customized fast code sequence in the td file.
154 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
155 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
156
157 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
158 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
159
160 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
161 for (MVT VT : MVT::integer_valuetypes()) {
162 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
163 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
164 }
165
166 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
167
168 // PowerPC has pre-inc load and store's.
169 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
170 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
171 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
172 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
173 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
174 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
175 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
176 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
177 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
178 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
179 if (!Subtarget.hasSPE()) {
180 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
181 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
182 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
183 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
184 }
185
186 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
187 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
188 for (MVT VT : ScalarIntVTs) {
189 setOperationAction(ISD::ADDC, VT, Legal);
190 setOperationAction(ISD::ADDE, VT, Legal);
191 setOperationAction(ISD::SUBC, VT, Legal);
192 setOperationAction(ISD::SUBE, VT, Legal);
193 }
194
195 if (Subtarget.useCRBits()) {
196 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
197
198 if (isPPC64 || Subtarget.hasFPCVT()) {
199 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
200 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
201 isPPC64 ? MVT::i64 : MVT::i32);
202 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
203 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
204 isPPC64 ? MVT::i64 : MVT::i32);
205 } else {
206 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
207 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
208 }
209
210 // PowerPC does not support direct load/store of condition registers.
211 setOperationAction(ISD::LOAD, MVT::i1, Custom);
212 setOperationAction(ISD::STORE, MVT::i1, Custom);
213
214 // FIXME: Remove this once the ANDI glue bug is fixed:
215 if (ANDIGlueBug)
216 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
217
218 for (MVT VT : MVT::integer_valuetypes()) {
219 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
220 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
221 setTruncStoreAction(VT, MVT::i1, Expand);
222 }
223
224 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
225 }
226
227 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
228 // PPC (the libcall is not available).
229 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
230 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
231
232 // We do not currently implement these libm ops for PowerPC.
233 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
234 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
235 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
236 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
237 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
238 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
239
240 // PowerPC has no SREM/UREM instructions unless we are on P9
241 // On P9 we may use a hardware instruction to compute the remainder.
242 // The instructions are not legalized directly because in the cases where the
243 // result of both the remainder and the division is required it is more
244 // efficient to compute the remainder from the result of the division rather
245 // than use the remainder instruction.
246 if (Subtarget.isISA3_0()) {
247 setOperationAction(ISD::SREM, MVT::i32, Custom);
248 setOperationAction(ISD::UREM, MVT::i32, Custom);
249 setOperationAction(ISD::SREM, MVT::i64, Custom);
250 setOperationAction(ISD::UREM, MVT::i64, Custom);
251 } else {
252 setOperationAction(ISD::SREM, MVT::i32, Expand);
253 setOperationAction(ISD::UREM, MVT::i32, Expand);
254 setOperationAction(ISD::SREM, MVT::i64, Expand);
255 setOperationAction(ISD::UREM, MVT::i64, Expand);
256 }
257
258 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
259 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
260 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
261 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
262 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
263 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
264 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
265 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
266 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
267
268 // We don't support sin/cos/sqrt/fmod/pow
269 setOperationAction(ISD::FSIN , MVT::f64, Expand);
270 setOperationAction(ISD::FCOS , MVT::f64, Expand);
271 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
272 setOperationAction(ISD::FREM , MVT::f64, Expand);
273 setOperationAction(ISD::FPOW , MVT::f64, Expand);
274 setOperationAction(ISD::FSIN , MVT::f32, Expand);
275 setOperationAction(ISD::FCOS , MVT::f32, Expand);
276 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
277 setOperationAction(ISD::FREM , MVT::f32, Expand);
278 setOperationAction(ISD::FPOW , MVT::f32, Expand);
279 if (Subtarget.hasSPE()) {
280 setOperationAction(ISD::FMA , MVT::f64, Expand);
281 setOperationAction(ISD::FMA , MVT::f32, Expand);
282 } else {
283 setOperationAction(ISD::FMA , MVT::f64, Legal);
284 setOperationAction(ISD::FMA , MVT::f32, Legal);
285 }
286
287 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
288
289 // If we're enabling GP optimizations, use hardware square root
290 if (!Subtarget.hasFSQRT() &&
291 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
292 Subtarget.hasFRE()))
293 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
294
295 if (!Subtarget.hasFSQRT() &&
296 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
297 Subtarget.hasFRES()))
298 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
299
300 if (Subtarget.hasFCPSGN()) {
301 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
302 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
303 } else {
304 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
305 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
306 }
307
308 if (Subtarget.hasFPRND()) {
309 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
310 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
311 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
312 setOperationAction(ISD::FROUND, MVT::f64, Legal);
313
314 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
315 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
316 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
317 setOperationAction(ISD::FROUND, MVT::f32, Legal);
318 }
319
320 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
321 // to speed up scalar BSWAP64.
322 // CTPOP or CTTZ were introduced in P8/P9 respectively
323 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
324 if (Subtarget.hasP9Vector())
325 setOperationAction(ISD::BSWAP, MVT::i64 , Custom);
326 else
327 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
328 if (Subtarget.isISA3_0()) {
329 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
330 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
331 } else {
332 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
333 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
334 }
335
336 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
337 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
338 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
339 } else {
340 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
341 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
342 }
343
344 // PowerPC does not have ROTR
345 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
346 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
347
348 if (!Subtarget.useCRBits()) {
349 // PowerPC does not have Select
350 setOperationAction(ISD::SELECT, MVT::i32, Expand);
351 setOperationAction(ISD::SELECT, MVT::i64, Expand);
352 setOperationAction(ISD::SELECT, MVT::f32, Expand);
353 setOperationAction(ISD::SELECT, MVT::f64, Expand);
354 }
355
356 // PowerPC wants to turn select_cc of FP into fsel when possible.
357 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
358 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
359
360 // PowerPC wants to optimize integer setcc a bit
361 if (!Subtarget.useCRBits())
362 setOperationAction(ISD::SETCC, MVT::i32, Custom);
363
364 // PowerPC does not have BRCOND which requires SetCC
365 if (!Subtarget.useCRBits())
366 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
367
368 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
369
370 if (Subtarget.hasSPE()) {
371 // SPE has built-in conversions
372 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
373 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
374 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
375 } else {
376 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
377 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
378
379 // PowerPC does not have [U|S]INT_TO_FP
380 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
381 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
382 }
383
384 if (Subtarget.hasDirectMove() && isPPC64) {
385 setOperationAction(ISD::BITCAST, MVT::f32, Legal);
386 setOperationAction(ISD::BITCAST, MVT::i32, Legal);
387 setOperationAction(ISD::BITCAST, MVT::i64, Legal);
388 setOperationAction(ISD::BITCAST, MVT::f64, Legal);
389 } else {
390 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
391 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
392 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
393 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
394 }
395
396 // We cannot sextinreg(i1). Expand to shifts.
397 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
398
399 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
400 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
401 // support continuation, user-level threading, and etc.. As a result, no
402 // other SjLj exception interfaces are implemented and please don't build
403 // your own exception handling based on them.
404 // LLVM/Clang supports zero-cost DWARF exception handling.
405 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
406 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
407
408 // We want to legalize GlobalAddress and ConstantPool nodes into the
409 // appropriate instructions to materialize the address.
410 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
411 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
412 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
413 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
414 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
415 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
416 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
417 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
418 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
419 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
420
421 // TRAP is legal.
422 setOperationAction(ISD::TRAP, MVT::Other, Legal);
423
424 // TRAMPOLINE is custom lowered.
425 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
426 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
427
428 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
429 setOperationAction(ISD::VASTART , MVT::Other, Custom);
430
431 if (Subtarget.isSVR4ABI()) {
432 if (isPPC64) {
433 // VAARG always uses double-word chunks, so promote anything smaller.
434 setOperationAction(ISD::VAARG, MVT::i1, Promote);
435 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
436 setOperationAction(ISD::VAARG, MVT::i8, Promote);
437 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
438 setOperationAction(ISD::VAARG, MVT::i16, Promote);
439 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
440 setOperationAction(ISD::VAARG, MVT::i32, Promote);
441 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
442 setOperationAction(ISD::VAARG, MVT::Other, Expand);
443 } else {
444 // VAARG is custom lowered with the 32-bit SVR4 ABI.
445 setOperationAction(ISD::VAARG, MVT::Other, Custom);
446 setOperationAction(ISD::VAARG, MVT::i64, Custom);
447 }
448 } else
449 setOperationAction(ISD::VAARG, MVT::Other, Expand);
450
451 if (Subtarget.isSVR4ABI() && !isPPC64)
452 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
453 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
454 else
455 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
456
457 // Use the default implementation.
458 setOperationAction(ISD::VAEND , MVT::Other, Expand);
459 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
460 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
461 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
462 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
463 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
464 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
465 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
466 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
467
468 // We want to custom lower some of our intrinsics.
469 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
470
471 // To handle counter-based loop conditions.
472 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
473
474 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
475 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
476 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
477 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
478
479 // Comparisons that require checking two conditions.
480 if (Subtarget.hasSPE()) {
481 setCondCodeAction(ISD::SETO, MVT::f32, Expand);
482 setCondCodeAction(ISD::SETO, MVT::f64, Expand);
483 setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
484 setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
485 }
486 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
487 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
488 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
489 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
490 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
491 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
492 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
493 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
494 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
495 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
496 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
497 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
498
499 if (Subtarget.has64BitSupport()) {
500 // They also have instructions for converting between i64 and fp.
501 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
502 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
503 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
504 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
505 // This is just the low 32 bits of a (signed) fp->i64 conversion.
506 // We cannot do this with Promote because i64 is not a legal type.
507 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
508
509 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
510 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
511 } else {
512 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
513 if (Subtarget.hasSPE())
514 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
515 else
516 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
517 }
518
519 // With the instructions enabled under FPCVT, we can do everything.
520 if (Subtarget.hasFPCVT()) {
521 if (Subtarget.has64BitSupport()) {
522 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
523 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
524 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
525 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
526 }
527
528 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
529 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
530 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
531 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
532 }
533
534 if (Subtarget.use64BitRegs()) {
535 // 64-bit PowerPC implementations can support i64 types directly
536 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
537 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
538 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
539 // 64-bit PowerPC wants to expand i128 shifts itself.
540 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
541 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
542 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
543 } else {
544 // 32-bit PowerPC wants to expand i64 shifts itself.
545 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
546 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
547 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
548 }
549
550 if (Subtarget.hasAltivec()) {
551 // First set operation action for all vector types to expand. Then we
552 // will selectively turn on ones that can be effectively codegen'd.
553 for (MVT VT : MVT::vector_valuetypes()) {
554 // add/sub are legal for all supported vector VT's.
555 setOperationAction(ISD::ADD, VT, Legal);
556 setOperationAction(ISD::SUB, VT, Legal);
557
558 // For v2i64, these are only valid with P8Vector. This is corrected after
559 // the loop.
560 setOperationAction(ISD::SMAX, VT, Legal);
561 setOperationAction(ISD::SMIN, VT, Legal);
562 setOperationAction(ISD::UMAX, VT, Legal);
563 setOperationAction(ISD::UMIN, VT, Legal);
564
565 if (Subtarget.hasVSX()) {
566 setOperationAction(ISD::FMAXNUM, VT, Legal);
567 setOperationAction(ISD::FMINNUM, VT, Legal);
568 }
569
570 // Vector instructions introduced in P8
571 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
572 setOperationAction(ISD::CTPOP, VT, Legal);
573 setOperationAction(ISD::CTLZ, VT, Legal);
574 }
575 else {
576 setOperationAction(ISD::CTPOP, VT, Expand);
577 setOperationAction(ISD::CTLZ, VT, Expand);
578 }
579
580 // Vector instructions introduced in P9
581 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
582 setOperationAction(ISD::CTTZ, VT, Legal);
583 else
584 setOperationAction(ISD::CTTZ, VT, Expand);
585
586 // We promote all shuffles to v16i8.
587 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
588 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
589
590 // We promote all non-typed operations to v4i32.
591 setOperationAction(ISD::AND , VT, Promote);
592 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
593 setOperationAction(ISD::OR , VT, Promote);
594 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
595 setOperationAction(ISD::XOR , VT, Promote);
596 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
597 setOperationAction(ISD::LOAD , VT, Promote);
598 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
599 setOperationAction(ISD::SELECT, VT, Promote);
600 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
601 setOperationAction(ISD::VSELECT, VT, Legal);
602 setOperationAction(ISD::SELECT_CC, VT, Promote);
603 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
604 setOperationAction(ISD::STORE, VT, Promote);
605 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
606
607 // No other operations are legal.
608 setOperationAction(ISD::MUL , VT, Expand);
609 setOperationAction(ISD::SDIV, VT, Expand);
610 setOperationAction(ISD::SREM, VT, Expand);
611 setOperationAction(ISD::UDIV, VT, Expand);
612 setOperationAction(ISD::UREM, VT, Expand);
613 setOperationAction(ISD::FDIV, VT, Expand);
614 setOperationAction(ISD::FREM, VT, Expand);
615 setOperationAction(ISD::FNEG, VT, Expand);
616 setOperationAction(ISD::FSQRT, VT, Expand);
617 setOperationAction(ISD::FLOG, VT, Expand);
618 setOperationAction(ISD::FLOG10, VT, Expand);
619 setOperationAction(ISD::FLOG2, VT, Expand);
620 setOperationAction(ISD::FEXP, VT, Expand);
621 setOperationAction(ISD::FEXP2, VT, Expand);
622 setOperationAction(ISD::FSIN, VT, Expand);
623 setOperationAction(ISD::FCOS, VT, Expand);
624 setOperationAction(ISD::FABS, VT, Expand);
625 setOperationAction(ISD::FFLOOR, VT, Expand);
626 setOperationAction(ISD::FCEIL, VT, Expand);
627 setOperationAction(ISD::FTRUNC, VT, Expand);
628 setOperationAction(ISD::FRINT, VT, Expand);
629 setOperationAction(ISD::FNEARBYINT, VT, Expand);
630 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
631 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
632 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
633 setOperationAction(ISD::MULHU, VT, Expand);
634 setOperationAction(ISD::MULHS, VT, Expand);
635 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
636 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
637 setOperationAction(ISD::UDIVREM, VT, Expand);
638 setOperationAction(ISD::SDIVREM, VT, Expand);
639 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
640 setOperationAction(ISD::FPOW, VT, Expand);
641 setOperationAction(ISD::BSWAP, VT, Expand);
642 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
643 setOperationAction(ISD::ROTL, VT, Expand);
644 setOperationAction(ISD::ROTR, VT, Expand);
645
646 for (MVT InnerVT : MVT::vector_valuetypes()) {
647 setTruncStoreAction(VT, InnerVT, Expand);
648 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
649 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
650 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
651 }
652 }
653 if (!Subtarget.hasP8Vector()) {
654 setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
655 setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
656 setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
657 setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
658 }
659
660 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
661 setOperationAction(ISD::ABS, VT, Custom);
662
663 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
664 // with merges, splats, etc.
665 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
666
667 // Vector truncates to sub-word integer that fit in an Altivec/VSX register
668 // are cheap, so handle them before they get expanded to scalar.
669 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
670 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
671 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
672 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
673 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
674
675 setOperationAction(ISD::AND , MVT::v4i32, Legal);
676 setOperationAction(ISD::OR , MVT::v4i32, Legal);
677 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
678 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
679 setOperationAction(ISD::SELECT, MVT::v4i32,
680 Subtarget.useCRBits() ? Legal : Expand);
681 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
682 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
683 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
684 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
685 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
686 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
687 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
688 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
689 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
690
691 // Without hasP8Altivec set, v2i64 SMAX isn't available.
692 // But ABS custom lowering requires SMAX support.
693 if (!Subtarget.hasP8Altivec())
694 setOperationAction(ISD::ABS, MVT::v2i64, Expand);
695
696 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
697 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
698 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
699 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
700
701 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
702 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
703
704 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
705 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
706 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
707 }
708
709 if (Subtarget.hasP8Altivec())
710 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
711 else
712 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
713
714 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
715 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
716
717 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
718 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
719
720 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
721 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
722 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
723 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
724
725 // Altivec does not contain unordered floating-point compare instructions
726 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
727 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
728 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
729 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
730
731 if (Subtarget.hasVSX()) {
732 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
733 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
734 if (Subtarget.hasP8Vector()) {
735 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
737 }
738 if (Subtarget.hasDirectMove() && isPPC64) {
739 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
740 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
741 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
742 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
743 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
744 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
746 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
747 }
748 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
749
750 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
751 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
752 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
753 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
754 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
755
756 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
757
758 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
759 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
760
761 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
762 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
763
764 // Share the Altivec comparison restrictions.
765 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
766 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
767 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
768 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
769
770 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
771 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
772
773 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
774
775 if (Subtarget.hasP8Vector())
776 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
777
778 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
779
780 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
781 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
782 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
783
784 if (Subtarget.hasP8Altivec()) {
785 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
786 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
787 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
788
789 // 128 bit shifts can be accomplished via 3 instructions for SHL and
790 // SRL, but not for SRA because of the instructions available:
791 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
792 // doing
793 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
794 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
795 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
796
797 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
798 }
799 else {
800 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
801 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
802 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
803
804 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
805
806 // VSX v2i64 only supports non-arithmetic operations.
807 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
808 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
809 }
810
811 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
812 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
813 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
814 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
815
816 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
817
818 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
819 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
820 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
821 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
822
823 // Custom handling for partial vectors of integers converted to
824 // floating point. We already have optimal handling for v2i32 through
825 // the DAG combine, so those aren't necessary.
826 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
827 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
828 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
829 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
830 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
831 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
832 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
833 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
834
835 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
836 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
837 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
838 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
839
840 if (Subtarget.hasDirectMove())
841 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
842 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
843
844 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
845 }
846
847 if (Subtarget.hasP8Altivec()) {
848 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
849 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
850 }
851
852 if (Subtarget.hasP9Vector()) {
853 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
854 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
855
856 // 128 bit shifts can be accomplished via 3 instructions for SHL and
857 // SRL, but not for SRA because of the instructions available:
858 // VS{RL} and VS{RL}O.
859 setOperationAction(ISD::SHL, MVT::v1i128, Legal);
860 setOperationAction(ISD::SRL, MVT::v1i128, Legal);
861 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
862
863 if (EnableQuadPrecision) {
864 addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
865 setOperationAction(ISD::FADD, MVT::f128, Legal);
866 setOperationAction(ISD::FSUB, MVT::f128, Legal);
867 setOperationAction(ISD::FDIV, MVT::f128, Legal);
868 setOperationAction(ISD::FMUL, MVT::f128, Legal);
869 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
870 // No extending loads to f128 on PPC.
871 for (MVT FPT : MVT::fp_valuetypes())
872 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
873 setOperationAction(ISD::FMA, MVT::f128, Legal);
874 setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
875 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
876 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
877 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
878 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
879 setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
880
881 setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
882 setOperationAction(ISD::FRINT, MVT::f128, Legal);
883 setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
884 setOperationAction(ISD::FCEIL, MVT::f128, Legal);
885 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
886 setOperationAction(ISD::FROUND, MVT::f128, Legal);
887
888 setOperationAction(ISD::SELECT, MVT::f128, Expand);
889 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
890 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
891 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
892 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
893 setOperationAction(ISD::BITCAST, MVT::i128, Custom);
894 // No implementation for these ops for PowerPC.
895 setOperationAction(ISD::FSIN , MVT::f128, Expand);
896 setOperationAction(ISD::FCOS , MVT::f128, Expand);
897 setOperationAction(ISD::FPOW, MVT::f128, Expand);
898 setOperationAction(ISD::FPOWI, MVT::f128, Expand);
899 setOperationAction(ISD::FREM, MVT::f128, Expand);
900 }
901 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
902
903 }
904
905 if (Subtarget.hasP9Altivec()) {
906 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
907 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
908 }
909 }
910
911 if (Subtarget.hasQPX()) {
912 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
913 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
914 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
915 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
916
917 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
918 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
919
920 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
921 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
922
923 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
924 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
925
926 if (!Subtarget.useCRBits())
927 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
928 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
929
930 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
931 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
932 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
933 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
934 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
935 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
936 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
937
938 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
939 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
940
941 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
942 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
943 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
944
945 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
946 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
947 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
948 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
949 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
950 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
951 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
952 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
953 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
954 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
955
956 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
957 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
958
959 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
960 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
961
962 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
963
964 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
965 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
966 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
967 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
968
969 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
970 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
971
972 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
973 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
974
975 if (!Subtarget.useCRBits())
976 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
977 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
978
979 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
980 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
981 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
982 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
983 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
984 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
986
987 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
988 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
989
990 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
991 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
992 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
993 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
994 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
995 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
996 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
997 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
998 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
999 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1000
1001 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1002 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1003
1004 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1005 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1006
1007 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1008
1009 setOperationAction(ISD::AND , MVT::v4i1, Legal);
1010 setOperationAction(ISD::OR , MVT::v4i1, Legal);
1011 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1012
1013 if (!Subtarget.useCRBits())
1014 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1015 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1016
1017 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
1018 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1019
1020 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1021 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1022 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1023 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1024 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1025 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1026 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1027
1028 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1029 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1030
1031 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1032
1033 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1034 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1035 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1036 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1037
1038 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1039 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1040 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1041 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1042
1043 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1044 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1045
1046 // These need to set FE_INEXACT, and so cannot be vectorized here.
1047 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1048 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1049
1050 if (TM.Options.UnsafeFPMath) {
1051 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1052 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1053
1054 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1055 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1056 } else {
1057 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1058 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1059
1060 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1061 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1062 }
1063 }
1064
1065 if (Subtarget.has64BitSupport())
1066 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1067
1068 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1069
1070 if (!isPPC64) {
1071 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
1072 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1073 }
1074
1075 setBooleanContents(ZeroOrOneBooleanContent);
1076
1077 if (Subtarget.hasAltivec()) {
1078 // Altivec instructions set fields to all zeros or all ones.
1079 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1080 }
1081
1082 if (!isPPC64) {
1083 // These libcalls are not available in 32-bit.
1084 setLibcallName(RTLIB::SHL_I128, nullptr);
1085 setLibcallName(RTLIB::SRL_I128, nullptr);
1086 setLibcallName(RTLIB::SRA_I128, nullptr);
1087 }
1088
1089 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1090
1091 // We have target-specific dag combine patterns for the following nodes:
1092 setTargetDAGCombine(ISD::ADD);
1093 setTargetDAGCombine(ISD::SHL);
1094 setTargetDAGCombine(ISD::SRA);
1095 setTargetDAGCombine(ISD::SRL);
1096 setTargetDAGCombine(ISD::MUL);
1097 setTargetDAGCombine(ISD::SINT_TO_FP);
1098 setTargetDAGCombine(ISD::BUILD_VECTOR);
1099 if (Subtarget.hasFPCVT())
1100 setTargetDAGCombine(ISD::UINT_TO_FP);
1101 setTargetDAGCombine(ISD::LOAD);
1102 setTargetDAGCombine(ISD::STORE);
1103 setTargetDAGCombine(ISD::BR_CC);
1104 if (Subtarget.useCRBits())
1105 setTargetDAGCombine(ISD::BRCOND);
1106 setTargetDAGCombine(ISD::BSWAP);
1107 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1108 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1109 setTargetDAGCombine(ISD::INTRINSIC_VOID);
1110
1111 setTargetDAGCombine(ISD::SIGN_EXTEND);
1112 setTargetDAGCombine(ISD::ZERO_EXTEND);
1113 setTargetDAGCombine(ISD::ANY_EXTEND);
1114
1115 setTargetDAGCombine(ISD::TRUNCATE);
1116
1117 if (Subtarget.useCRBits()) {
1118 setTargetDAGCombine(ISD::TRUNCATE);
1119 setTargetDAGCombine(ISD::SETCC);
1120 setTargetDAGCombine(ISD::SELECT_CC);
1121 }
1122
1123 // Use reciprocal estimates.
1124 if (TM.Options.UnsafeFPMath) {
1125 setTargetDAGCombine(ISD::FDIV);
1126 setTargetDAGCombine(ISD::FSQRT);
1127 }
1128
1129 if (Subtarget.hasP9Altivec()) {
1130 setTargetDAGCombine(ISD::ABS);
1131 setTargetDAGCombine(ISD::VSELECT);
1132 }
1133
1134 // Darwin long double math library functions have $LDBL128 appended.
1135 if (Subtarget.isDarwin()) {
1136 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1137 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1138 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1139 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1140 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1141 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1142 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1143 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1144 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1145 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1146 }
1147
1148 if (EnableQuadPrecision) {
1149 setLibcallName(RTLIB::LOG_F128, "logf128");
1150 setLibcallName(RTLIB::LOG2_F128, "log2f128");
1151 setLibcallName(RTLIB::LOG10_F128, "log10f128");
1152 setLibcallName(RTLIB::EXP_F128, "expf128");
1153 setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1154 setLibcallName(RTLIB::SIN_F128, "sinf128");
1155 setLibcallName(RTLIB::COS_F128, "cosf128");
1156 setLibcallName(RTLIB::POW_F128, "powf128");
1157 setLibcallName(RTLIB::FMIN_F128, "fminf128");
1158 setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1159 setLibcallName(RTLIB::POWI_F128, "__powikf2");
1160 setLibcallName(RTLIB::REM_F128, "fmodf128");
1161 }
1162
1163 // With 32 condition bits, we don't need to sink (and duplicate) compares
1164 // aggressively in CodeGenPrep.
1165 if (Subtarget.useCRBits()) {
1166 setHasMultipleConditionRegisters();
1167 setJumpIsExpensive();
1168 }
1169
1170 setMinFunctionAlignment(2);
1171 if (Subtarget.isDarwin())
1172 setPrefFunctionAlignment(4);
1173
1174 switch (Subtarget.getDarwinDirective()) {
1175 default: break;
1176 case PPC::DIR_970:
1177 case PPC::DIR_A2:
1178 case PPC::DIR_E500:
1179 case PPC::DIR_E500mc:
1180 case PPC::DIR_E5500:
1181 case PPC::DIR_PWR4:
1182 case PPC::DIR_PWR5:
1183 case PPC::DIR_PWR5X:
1184 case PPC::DIR_PWR6:
1185 case PPC::DIR_PWR6X:
1186 case PPC::DIR_PWR7:
1187 case PPC::DIR_PWR8:
1188 case PPC::DIR_PWR9:
1189 setPrefFunctionAlignment(4);
1190 setPrefLoopAlignment(4);
1191 break;
1192 }
1193
1194 if (Subtarget.enableMachineScheduler())
1195 setSchedulingPreference(Sched::Source);
1196 else
1197 setSchedulingPreference(Sched::Hybrid);
1198
1199 computeRegisterProperties(STI.getRegisterInfo());
1200
1201 // The Freescale cores do better with aggressive inlining of memcpy and
1202 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1203 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1204 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1205 MaxStoresPerMemset = 32;
1206 MaxStoresPerMemsetOptSize = 16;
1207 MaxStoresPerMemcpy = 32;
1208 MaxStoresPerMemcpyOptSize = 8;
1209 MaxStoresPerMemmove = 32;
1210 MaxStoresPerMemmoveOptSize = 8;
1211 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1212 // The A2 also benefits from (very) aggressive inlining of memcpy and
1213 // friends. The overhead of a the function call, even when warm, can be
1214 // over one hundred cycles.
1215 MaxStoresPerMemset = 128;
1216 MaxStoresPerMemcpy = 128;
1217 MaxStoresPerMemmove = 128;
1218 MaxLoadsPerMemcmp = 128;
1219 } else {
1220 MaxLoadsPerMemcmp = 8;
1221 MaxLoadsPerMemcmpOptSize = 4;
1222 }
1223}
1224
1225/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1226/// the desired ByVal argument alignment.
1227static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1228 unsigned MaxMaxAlign) {
1229 if (MaxAlign == MaxMaxAlign)
1230 return;
1231 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1232 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1233 MaxAlign = 32;
1234 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1235 MaxAlign = 16;
1236 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1237 unsigned EltAlign = 0;
1238 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1239 if (EltAlign > MaxAlign)
1240 MaxAlign = EltAlign;
1241 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1242 for (auto *EltTy : STy->elements()) {
1243 unsigned EltAlign = 0;
1244 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1245 if (EltAlign > MaxAlign)
1246 MaxAlign = EltAlign;
1247 if (MaxAlign == MaxMaxAlign)
1248 break;
1249 }
1250 }
1251}
1252
1253/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1254/// function arguments in the caller parameter area.
1255unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1256 const DataLayout &DL) const {
1257 // Darwin passes everything on 4 byte boundary.
1258 if (Subtarget.isDarwin())
1259 return 4;
1260
1261 // 16byte and wider vectors are passed on 16byte boundary.
1262 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1263 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1264 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1265 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1266 return Align;
1267}
1268
1269unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1270 CallingConv:: ID CC,
1271 EVT VT) const {
1272 if (Subtarget.hasSPE() && VT == MVT::f64)
1273 return 2;
1274 return PPCTargetLowering::getNumRegisters(Context, VT);
1275}
1276
1277MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1278 CallingConv:: ID CC,
1279 EVT VT) const {
1280 if (Subtarget.hasSPE() && VT == MVT::f64)
1281 return MVT::i32;
1282 return PPCTargetLowering::getRegisterType(Context, VT);
1283}
1284
1285bool PPCTargetLowering::useSoftFloat() const {
1286 return Subtarget.useSoftFloat();
1287}
1288
1289bool PPCTargetLowering::hasSPE() const {
1290 return Subtarget.hasSPE();
1291}
1292
1293const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1294 switch ((PPCISD::NodeType)Opcode) {
1295 case PPCISD::FIRST_NUMBER: break;
1296 case PPCISD::FSEL: return "PPCISD::FSEL";
1297 case PPCISD::FCFID: return "PPCISD::FCFID";
1298 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1299 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1300 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1301 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1302 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1303 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1304 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1305 case PPCISD::FP_TO_UINT_IN_VSR:
1306 return "PPCISD::FP_TO_UINT_IN_VSR,";
1307 case PPCISD::FP_TO_SINT_IN_VSR:
1308 return "PPCISD::FP_TO_SINT_IN_VSR";
1309 case PPCISD::FRE: return "PPCISD::FRE";
1310 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1311 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1312 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
1313 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
1314 case PPCISD::VPERM: return "PPCISD::VPERM";
1315 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1316 case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1317 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE";
1318 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1319 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1320 case PPCISD::CMPB: return "PPCISD::CMPB";
1321 case PPCISD::Hi: return "PPCISD::Hi";
1322 case PPCISD::Lo: return "PPCISD::Lo";
1323 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1324 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1325 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1326 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1327 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1328 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1329 case PPCISD::SRL: return "PPCISD::SRL";
1330 case PPCISD::SRA: return "PPCISD::SRA";
1331 case PPCISD::SHL: return "PPCISD::SHL";
1332 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1333 case PPCISD::CALL: return "PPCISD::CALL";
1334 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1335 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1336 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1337 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1338 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1339 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1340 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1341 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1342 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1343 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1344 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1345 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1346 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1347 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1348 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1349 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1350 case PPCISD::VCMP: return "PPCISD::VCMP";
1351 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1352 case PPCISD::LBRX: return "PPCISD::LBRX";
1353 case PPCISD::STBRX: return "PPCISD::STBRX";
1354 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1355 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1356 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1357 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1358 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1359 case PPCISD::SExtVElems: return "PPCISD::SExtVElems";
1360 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1361 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1362 case PPCISD::ST_VSR_SCAL_INT:
1363 return "PPCISD::ST_VSR_SCAL_INT";
1364 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1365 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1366 case PPCISD::BDZ: return "PPCISD::BDZ";
1367 case PPCISD::MFFS: return "PPCISD::MFFS";
1368 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1369 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1370 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1371 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1372 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1373 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1374 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1375 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1376 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1377 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1378 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1379 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1380 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1381 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1382 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1383 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1384 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1385 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1386 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1387 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1388 case PPCISD::SC: return "PPCISD::SC";
1389 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1390 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1391 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1392 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1393 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1394 case PPCISD::VABSD: return "PPCISD::VABSD";
1395 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1396 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1397 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1398 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1399 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1400 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1401 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1402 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
1403 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
1404 case PPCISD::FP_EXTEND_LH: return "PPCISD::FP_EXTEND_LH";
1405 }
1406 return nullptr;
1407}
1408
1409EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1410 EVT VT) const {
1411 if (!VT.isVector())
1412 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1413
1414 if (Subtarget.hasQPX())
1415 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1416
1417 return VT.changeVectorElementTypeToInteger();
1418}
1419
1420bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1421 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1422 return true;
1423}
1424
1425//===----------------------------------------------------------------------===//
1426// Node matching predicates, for use by the tblgen matching code.
1427//===----------------------------------------------------------------------===//
1428
1429/// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1430static bool isFloatingPointZero(SDValue Op) {
1431 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1432 return CFP->getValueAPF().isZero();
1433 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1434 // Maybe this has already been legalized into the constant pool?
1435 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1436 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1437 return CFP->getValueAPF().isZero();
1438 }
1439 return false;
1440}
1441
1442/// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1443/// true if Op is undef or if it matches the specified value.
1444static bool isConstantOrUndef(int Op, int Val) {
1445 return Op < 0 || Op == Val;
1446}
1447
1448/// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1449/// VPKUHUM instruction.
1450/// The ShuffleKind distinguishes between big-endian operations with
1451/// two different inputs (0), either-endian operations with two identical
1452/// inputs (1), and little-endian operations with two different inputs (2).
1453/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1454bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1455 SelectionDAG &DAG) {
1456 bool IsLE = DAG.getDataLayout().isLittleEndian();
1457 if (ShuffleKind == 0) {
1458 if (IsLE)
1459 return false;
1460 for (unsigned i = 0; i != 16; ++i)
1461 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1462 return false;
1463 } else if (ShuffleKind == 2) {
1464 if (!IsLE)
1465 return false;
1466 for (unsigned i = 0; i != 16; ++i)
1467 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1468 return false;
1469 } else if (ShuffleKind == 1) {
1470 unsigned j = IsLE ? 0 : 1;
1471 for (unsigned i = 0; i != 8; ++i)
1472 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1473 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1474 return false;
1475 }
1476 return true;
1477}
1478
1479/// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1480/// VPKUWUM instruction.
1481/// The ShuffleKind distinguishes between big-endian operations with
1482/// two different inputs (0), either-endian operations with two identical
1483/// inputs (1), and little-endian operations with two different inputs (2).
1484/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1485bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1486 SelectionDAG &DAG) {
1487 bool IsLE = DAG.getDataLayout().isLittleEndian();
1488 if (ShuffleKind == 0) {
1489 if (IsLE)
1490 return false;
1491 for (unsigned i = 0; i != 16; i += 2)
1492 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1493 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1494 return false;
1495 } else if (ShuffleKind == 2) {
1496 if (!IsLE)
1497 return false;
1498 for (unsigned i = 0; i != 16; i += 2)
1499 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1500 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1501 return false;
1502 } else if (ShuffleKind == 1) {
1503 unsigned j = IsLE ? 0 : 2;
1504 for (unsigned i = 0; i != 8; i += 2)
1505 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1506 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1507 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1508 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1509 return false;
1510 }
1511 return true;
1512}
1513
1514/// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1515/// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1516/// current subtarget.
1517///
1518/// The ShuffleKind distinguishes between big-endian operations with
1519/// two different inputs (0), either-endian operations with two identical
1520/// inputs (1), and little-endian operations with two different inputs (2).
1521/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1522bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1523 SelectionDAG &DAG) {
1524 const PPCSubtarget& Subtarget =
1525 static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1526 if (!Subtarget.hasP8Vector())
1527 return false;
1528
1529 bool IsLE = DAG.getDataLayout().isLittleEndian();
1530 if (ShuffleKind == 0) {
1531 if (IsLE)
1532 return false;
1533 for (unsigned i = 0; i != 16; i += 4)
1534 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1535 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1536 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1537 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1538 return false;
1539 } else if (ShuffleKind == 2) {
1540 if (!IsLE)
1541 return false;
1542 for (unsigned i = 0; i != 16; i += 4)
1543 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1544 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1545 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1546 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1547 return false;
1548 } else if (ShuffleKind == 1) {
1549 unsigned j = IsLE ? 0 : 4;
1550 for (unsigned i = 0; i != 8; i += 4)
1551 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1552 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1553 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1554 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1555 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1556 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1557 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1558 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1559 return false;
1560 }
1561 return true;
1562}
1563
1564/// isVMerge - Common function, used to match vmrg* shuffles.
1565///
1566static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1567 unsigned LHSStart, unsigned RHSStart) {
1568 if (N->getValueType(0) != MVT::v16i8)
1569 return false;
1570 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1571 "Unsupported merge size!");
1572
1573 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1574 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1575 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1576 LHSStart+j+i*UnitSize) ||
1577 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1578 RHSStart+j+i*UnitSize))
1579 return false;
1580 }
1581 return true;
1582}
1583
1584/// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1585/// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1586/// The ShuffleKind distinguishes between big-endian merges with two
1587/// different inputs (0), either-endian merges with two identical inputs (1),
1588/// and little-endian merges with two different inputs (2). For the latter,
1589/// the input operands are swapped (see PPCInstrAltivec.td).
1590bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1591 unsigned ShuffleKind, SelectionDAG &DAG) {
1592 if (DAG.getDataLayout().isLittleEndian()) {
1593 if (ShuffleKind == 1) // unary
1594 return isVMerge(N, UnitSize, 0, 0);
1595 else if (ShuffleKind == 2) // swapped
1596 return isVMerge(N, UnitSize, 0, 16);
1597 else
1598 return false;
1599 } else {
1600 if (ShuffleKind == 1) // unary
1601 return isVMerge(N, UnitSize, 8, 8);
1602 else if (ShuffleKind == 0) // normal
1603 return isVMerge(N, UnitSize, 8, 24);
1604 else
1605 return false;
1606 }
1607}
1608
1609/// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1610/// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1611/// The ShuffleKind distinguishes between big-endian merges with two
1612/// different inputs (0), either-endian merges with two identical inputs (1),
1613/// and little-endian merges with two different inputs (2). For the latter,
1614/// the input operands are swapped (see PPCInstrAltivec.td).
1615bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1616 unsigned ShuffleKind, SelectionDAG &DAG) {
1617 if (DAG.getDataLayout().isLittleEndian()) {
1618 if (ShuffleKind == 1) // unary
1619 return isVMerge(N, UnitSize, 8, 8);
1620 else if (ShuffleKind == 2) // swapped
1621 return isVMerge(N, UnitSize, 8, 24);
1622 else
1623 return false;
1624 } else {
1625 if (ShuffleKind == 1) // unary
1626 return isVMerge(N, UnitSize, 0, 0);
1627 else if (ShuffleKind == 0) // normal
1628 return isVMerge(N, UnitSize, 0, 16);
1629 else
1630 return false;
1631 }
1632}
1633
1634/**
1635 * Common function used to match vmrgew and vmrgow shuffles
1636 *
1637 * The indexOffset determines whether to look for even or odd words in
1638 * the shuffle mask. This is based on the of the endianness of the target
1639 * machine.
1640 * - Little Endian:
1641 * - Use offset of 0 to check for odd elements
1642 * - Use offset of 4 to check for even elements
1643 * - Big Endian:
1644 * - Use offset of 0 to check for even elements
1645 * - Use offset of 4 to check for odd elements
1646 * A detailed description of the vector element ordering for little endian and
1647 * big endian can be found at
1648 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1649 * Targeting your applications - what little endian and big endian IBM XL C/C++
1650 * compiler differences mean to you
1651 *
1652 * The mask to the shuffle vector instruction specifies the indices of the
1653 * elements from the two input vectors to place in the result. The elements are
1654 * numbered in array-access order, starting with the first vector. These vectors
1655 * are always of type v16i8, thus each vector will contain 16 elements of size
1656 * 8. More info on the shuffle vector can be found in the
1657 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1658 * Language Reference.
1659 *
1660 * The RHSStartValue indicates whether the same input vectors are used (unary)
1661 * or two different input vectors are used, based on the following:
1662 * - If the instruction uses the same vector for both inputs, the range of the
1663 * indices will be 0 to 15. In this case, the RHSStart value passed should
1664 * be 0.
1665 * - If the instruction has two different vectors then the range of the
1666 * indices will be 0 to 31. In this case, the RHSStart value passed should
1667 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1668 * to 31 specify elements in the second vector).
1669 *
1670 * \param[in] N The shuffle vector SD Node to analyze
1671 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1672 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1673 * vector to the shuffle_vector instruction
1674 * \return true iff this shuffle vector represents an even or odd word merge
1675 */
1676static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1677 unsigned RHSStartValue) {
1678 if (N->getValueType(0) != MVT::v16i8)
1679 return false;
1680
1681 for (unsigned i = 0; i < 2; ++i)
1682 for (unsigned j = 0; j < 4; ++j)
1683 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1684 i*RHSStartValue+j+IndexOffset) ||
1685 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1686 i*RHSStartValue+j+IndexOffset+8))
1687 return false;
1688 return true;
1689}
1690
1691/**
1692 * Determine if the specified shuffle mask is suitable for the vmrgew or
1693 * vmrgow instructions.
1694 *
1695 * \param[in] N The shuffle vector SD Node to analyze
1696 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1697 * \param[in] ShuffleKind Identify the type of merge:
1698 * - 0 = big-endian merge with two different inputs;
1699 * - 1 = either-endian merge with two identical inputs;
1700 * - 2 = little-endian merge with two different inputs (inputs are swapped for
1701 * little-endian merges).
1702 * \param[in] DAG The current SelectionDAG
1703 * \return true iff this shuffle mask
1704 */
1705bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1706 unsigned ShuffleKind, SelectionDAG &DAG) {
1707 if (DAG.getDataLayout().isLittleEndian()) {
1708 unsigned indexOffset = CheckEven ? 4 : 0;
1709 if (ShuffleKind == 1) // Unary
1710 return isVMerge(N, indexOffset, 0);
1711 else if (ShuffleKind == 2) // swapped
1712 return isVMerge(N, indexOffset, 16);
1713 else
1714 return false;
1715 }
1716 else {
1717 unsigned indexOffset = CheckEven ? 0 : 4;
1718 if (ShuffleKind == 1) // Unary
1719 return isVMerge(N, indexOffset, 0);
1720 else if (ShuffleKind == 0) // Normal
1721 return isVMerge(N, indexOffset, 16);
1722 else
1723 return false;
1724 }
1725 return false;
1726}
1727
1728/// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1729/// amount, otherwise return -1.
1730/// The ShuffleKind distinguishes between big-endian operations with two
1731/// different inputs (0), either-endian operations with two identical inputs
1732/// (1), and little-endian operations with two different inputs (2). For the
1733/// latter, the input operands are swapped (see PPCInstrAltivec.td).
1734int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1735 SelectionDAG &DAG) {
1736 if (N->getValueType(0) != MVT::v16i8)
1737 return -1;
1738
1739 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1740
1741 // Find the first non-undef value in the shuffle mask.
1742 unsigned i;
1743 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1744 /*search*/;
1745
1746 if (i == 16) return -1; // all undef.
1747
1748 // Otherwise, check to see if the rest of the elements are consecutively
1749 // numbered from this value.
1750 unsigned ShiftAmt = SVOp->getMaskElt(i);
1751 if (ShiftAmt < i) return -1;
1752
1753 ShiftAmt -= i;
1754 bool isLE = DAG.getDataLayout().isLittleEndian();
1755
1756 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1757 // Check the rest of the elements to see if they are consecutive.
1758 for (++i; i != 16; ++i)
1759 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1760 return -1;
1761 } else if (ShuffleKind == 1) {
1762 // Check the rest of the elements to see if they are consecutive.
1763 for (++i; i != 16; ++i)
1764 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1765 return -1;
1766 } else
1767 return -1;
1768
1769 if (isLE)
1770 ShiftAmt = 16 - ShiftAmt;
1771
1772 return ShiftAmt;
1773}
1774
1775/// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1776/// specifies a splat of a single element that is suitable for input to
1777/// VSPLTB/VSPLTH/VSPLTW.
1778bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1779 assert(N->getValueType(0) == MVT::v16i8 &&
1780 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1781
1782 // The consecutive indices need to specify an element, not part of two
1783 // different elements. So abandon ship early if this isn't the case.
1784 if (N->getMaskElt(0) % EltSize != 0)
1785 return false;
1786
1787 // This is a splat operation if each element of the permute is the same, and
1788 // if the value doesn't reference the second vector.
1789 unsigned ElementBase = N->getMaskElt(0);
1790
1791 // FIXME: Handle UNDEF elements too!
1792 if (ElementBase >= 16)
1793 return false;
1794
1795 // Check that the indices are consecutive, in the case of a multi-byte element
1796 // splatted with a v16i8 mask.
1797 for (unsigned i = 1; i != EltSize; ++i)
1798 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1799 return false;
1800
1801 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1802 if (N->getMaskElt(i) < 0) continue;
1803 for (unsigned j = 0; j != EltSize; ++j)
1804 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1805 return false;
1806 }
1807 return true;
1808}
1809
1810/// Check that the mask is shuffling N byte elements. Within each N byte
1811/// element of the mask, the indices could be either in increasing or
1812/// decreasing order as long as they are consecutive.
1813/// \param[in] N the shuffle vector SD Node to analyze
1814/// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1815/// Word/DoubleWord/QuadWord).
1816/// \param[in] StepLen the delta indices number among the N byte element, if
1817/// the mask is in increasing/decreasing order then it is 1/-1.
1818/// \return true iff the mask is shuffling N byte elements.
1819static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1820 int StepLen) {
1821 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1822 "Unexpected element width.");
1823 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1824
1825 unsigned NumOfElem = 16 / Width;
1826 unsigned MaskVal[16]; // Width is never greater than 16
1827 for (unsigned i = 0; i < NumOfElem; ++i) {
1828 MaskVal[0] = N->getMaskElt(i * Width);
1829 if ((StepLen == 1) && (MaskVal[0] % Width)) {
1830 return false;
1831 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1832 return false;
1833 }
1834
1835 for (unsigned int j = 1; j < Width; ++j) {
1836 MaskVal[j] = N->getMaskElt(i * Width + j);
1837 if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1838 return false;
1839 }
1840 }
1841 }
1842
1843 return true;
1844}
1845
1846bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1847 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1848 if (!isNByteElemShuffleMask(N, 4, 1))
1849 return false;
1850
1851 // Now we look at mask elements 0,4,8,12
1852 unsigned M0 = N->getMaskElt(0) / 4;
1853 unsigned M1 = N->getMaskElt(4) / 4;
1854 unsigned M2 = N->getMaskElt(8) / 4;
1855 unsigned M3 = N->getMaskElt(12) / 4;
1856 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1857 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1858
1859 // Below, let H and L be arbitrary elements of the shuffle mask
1860 // where H is in the range [4,7] and L is in the range [0,3].
1861 // H, 1, 2, 3 or L, 5, 6, 7
1862 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1863 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1864 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1865 InsertAtByte = IsLE ? 12 : 0;
1866 Swap = M0 < 4;
1867 return true;
1868 }
1869 // 0, H, 2, 3 or 4, L, 6, 7
1870 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1871 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1872 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1873 InsertAtByte = IsLE ? 8 : 4;
1874 Swap = M1 < 4;
1875 return true;
1876 }
1877 // 0, 1, H, 3 or 4, 5, L, 7
1878 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1879 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1880 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1881 InsertAtByte = IsLE ? 4 : 8;
1882 Swap = M2 < 4;
1883 return true;
1884 }
1885 // 0, 1, 2, H or 4, 5, 6, L
1886 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1887 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1888 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1889 InsertAtByte = IsLE ? 0 : 12;
1890 Swap = M3 < 4;
1891 return true;
1892 }
1893
1894 // If both vector operands for the shuffle are the same vector, the mask will
1895 // contain only elements from the first one and the second one will be undef.
1896 if (N->getOperand(1).isUndef()) {
1897 ShiftElts = 0;
1898 Swap = true;
1899 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1900 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1901 InsertAtByte = IsLE ? 12 : 0;
1902 return true;
1903 }
1904 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1905 InsertAtByte = IsLE ? 8 : 4;
1906 return true;
1907 }
1908 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1909 InsertAtByte = IsLE ? 4 : 8;
1910 return true;
1911 }
1912 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1913 InsertAtByte = IsLE ? 0 : 12;
1914 return true;
1915 }
1916 }
1917
1918 return false;
1919}
1920
1921bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1922 bool &Swap, bool IsLE) {
1923 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1924 // Ensure each byte index of the word is consecutive.
1925 if (!isNByteElemShuffleMask(N, 4, 1))
1926 return false;
1927
1928 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1929 unsigned M0 = N->getMaskElt(0) / 4;
1930 unsigned M1 = N->getMaskElt(4) / 4;
1931 unsigned M2 = N->getMaskElt(8) / 4;
1932 unsigned M3 = N->getMaskElt(12) / 4;
1933
1934 // If both vector operands for the shuffle are the same vector, the mask will
1935 // contain only elements from the first one and the second one will be undef.
1936 if (N->getOperand(1).isUndef()) {
1937 assert(M0 < 4 && "Indexing into an undef vector?");
1938 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1939 return false;
1940
1941 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1942 Swap = false;
1943 return true;
1944 }
1945
1946 // Ensure each word index of the ShuffleVector Mask is consecutive.
1947 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1948 return false;
1949
1950 if (IsLE) {
1951 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1952 // Input vectors don't need to be swapped if the leading element
1953 // of the result is one of the 3 left elements of the second vector
1954 // (or if there is no shift to be done at all).
1955 Swap = false;
1956 ShiftElts = (8 - M0) % 8;
1957 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1958 // Input vectors need to be swapped if the leading element
1959 // of the result is one of the 3 left elements of the first vector
1960 // (or if we're shifting by 4 - thereby simply swapping the vectors).
1961 Swap = true;
1962 ShiftElts = (4 - M0) % 4;
1963 }
1964
1965 return true;
1966 } else { // BE
1967 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1968 // Input vectors don't need to be swapped if the leading element
1969 // of the result is one of the 4 elements of the first vector.
1970 Swap = false;
1971 ShiftElts = M0;
1972 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1973 // Input vectors need to be swapped if the leading element
1974 // of the result is one of the 4 elements of the right vector.
1975 Swap = true;
1976 ShiftElts = M0 - 4;
1977 }
1978
1979 return true;
1980 }
1981}
1982
1983bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1984 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1985
1986 if (!isNByteElemShuffleMask(N, Width, -1))
1987 return false;
1988
1989 for (int i = 0; i < 16; i += Width)
1990 if (N->getMaskElt(i) != i + Width - 1)
1991 return false;
1992
1993 return true;
1994}
1995
1996bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1997 return isXXBRShuffleMaskHelper(N, 2);
1998}
1999
2000bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2001 return isXXBRShuffleMaskHelper(N, 4);
2002}
2003
2004bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2005 return isXXBRShuffleMaskHelper(N, 8);
2006}
2007
2008bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2009 return isXXBRShuffleMaskHelper(N, 16);
2010}
2011
2012/// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2013/// if the inputs to the instruction should be swapped and set \p DM to the
2014/// value for the immediate.
2015/// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2016/// AND element 0 of the result comes from the first input (LE) or second input
2017/// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2018/// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2019/// mask.
2020bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2021 bool &Swap, bool IsLE) {
2022 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2023
2024 // Ensure each byte index of the double word is consecutive.
2025 if (!isNByteElemShuffleMask(N, 8, 1))
2026 return false;
2027
2028 unsigned M0 = N->getMaskElt(0) / 8;
2029 unsigned M1 = N->getMaskElt(8) / 8;
2030 assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2031
2032 // If both vector operands for the shuffle are the same vector, the mask will
2033 // contain only elements from the first one and the second one will be undef.
2034 if (N->getOperand(1).isUndef()) {
2035 if ((M0 | M1) < 2) {
2036 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2037 Swap = false;
2038 return true;
2039 } else
2040 return false;
2041 }
2042
2043 if (IsLE) {
2044 if (M0 > 1 && M1 < 2) {
2045 Swap = false;
2046 } else if (M0 < 2 && M1 > 1) {
2047 M0 = (M0 + 2) % 4;
2048 M1 = (M1 + 2) % 4;
2049 Swap = true;
2050 } else
2051 return false;
2052
2053 // Note: if control flow comes here that means Swap is already set above
2054 DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2055 return true;
2056 } else { // BE
2057 if (M0 < 2 && M1 > 1) {
2058 Swap = false;
2059 } else if (M0 > 1 && M1 < 2) {
2060 M0 = (M0 + 2) % 4;
2061 M1 = (M1 + 2) % 4;
2062 Swap = true;
2063 } else
2064 return false;
2065
2066 // Note: if control flow comes here that means Swap is already set above
2067 DM = (M0 << 1) + (M1 & 1);
2068 return true;
2069 }
2070}
2071
2072
2073/// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
2074/// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
2075unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
2076 SelectionDAG &DAG) {
2077 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2078 assert(isSplatShuffleMask(SVOp, EltSize));
2079 if (DAG.getDataLayout().isLittleEndian())
2080 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2081 else
2082 return SVOp->getMaskElt(0) / EltSize;
2083}
2084
2085/// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2086/// by using a vspltis[bhw] instruction of the specified element size, return
2087/// the constant being splatted. The ByteSize field indicates the number of
2088/// bytes of each element [124] -> [bhw].
2089SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2090 SDValue OpVal(nullptr, 0);
2091
2092 // If ByteSize of the splat is bigger than the element size of the
2093 // build_vector, then we have a case where we are checking for a splat where
2094 // multiple elements of the buildvector are folded together into a single
2095 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2096 unsigned EltSize = 16/N->getNumOperands();
2097 if (EltSize < ByteSize) {
2098 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2099 SDValue UniquedVals[4];
2100 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2101
2102 // See if all of the elements in the buildvector agree across.
2103 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2104 if (N->getOperand(i).isUndef()) continue;
2105 // If the element isn't a constant, bail fully out.
2106 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2107
2108 if (!UniquedVals[i&(Multiple-1)].getNode())
2109 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2110 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2111 return SDValue(); // no match.
2112 }
2113
2114 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2115 // either constant or undef values that are identical for each chunk. See
2116 // if these chunks can form into a larger vspltis*.
2117
2118 // Check to see if all of the leading entries are either 0 or -1. If
2119 // neither, then this won't fit into the immediate field.
2120 bool LeadingZero = true;
2121 bool LeadingOnes = true;
2122 for (unsigned i = 0; i != Multiple-1; ++i) {
2123 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2124
2125 LeadingZero &= isNullConstant(UniquedVals[i]);
2126 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2127 }
2128 // Finally, check the least significant entry.
2129 if (LeadingZero) {
2130 if (!UniquedVals[Multiple-1].getNode())
2131 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2132 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2133 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2134 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2135 }
2136 if (LeadingOnes) {
2137 if (!UniquedVals[Multiple-1].getNode())
2138 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2139 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2140 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2141 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2142 }
2143
2144 return SDValue();
2145 }
2146
2147 // Check to see if this buildvec has a single non-undef value in its elements.
2148 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2149 if (N->getOperand(i).isUndef()) continue;
2150 if (!OpVal.getNode())
2151 OpVal = N->getOperand(i);
2152 else if (OpVal != N->getOperand(i))
2153 return SDValue();
2154 }
2155
2156 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2157
2158 unsigned ValSizeInBytes = EltSize;
2159 uint64_t Value = 0;
2160 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2161 Value = CN->getZExtValue();
2162 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2163 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2164 Value = FloatToBits(CN->getValueAPF().convertToFloat());
2165 }
2166
2167 // If the splat value is larger than the element value, then we can never do
2168 // this splat. The only case that we could fit the replicated bits into our
2169 // immediate field for would be zero, and we prefer to use vxor for it.
2170 if (ValSizeInBytes < ByteSize) return SDValue();
2171
2172 // If the element value is larger than the splat value, check if it consists
2173 // of a repeated bit pattern of size ByteSize.
2174 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2175 return SDValue();
2176
2177 // Properly sign extend the value.
2178 int MaskVal = SignExtend32(Value, ByteSize * 8);
2179
2180 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2181 if (MaskVal == 0) return SDValue();
2182
2183 // Finally, if this value fits in a 5 bit sext field, return it
2184 if (SignExtend32<5>(MaskVal) == MaskVal)
2185 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2186 return SDValue();
2187}
2188
2189/// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2190/// amount, otherwise return -1.
2191int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2192 EVT VT = N->getValueType(0);
2193 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2194 return -1;
2195
2196 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2197
2198 // Find the first non-undef value in the shuffle mask.
2199 unsigned i;
2200 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2201 /*search*/;
2202
2203 if (i == 4) return -1; // all undef.
2204
2205 // Otherwise, check to see if the rest of the elements are consecutively
2206 // numbered from this value.
2207 unsigned ShiftAmt = SVOp->getMaskElt(i);
2208 if (ShiftAmt < i) return -1;
2209 ShiftAmt -= i;
2210
2211 // Check the rest of the elements to see if they are consecutive.
2212 for (++i; i != 4; ++i)
2213 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2214 return -1;
2215
2216 return ShiftAmt;
2217}
2218
2219//===----------------------------------------------------------------------===//
2220// Addressing Mode Selection
2221//===----------------------------------------------------------------------===//
2222
2223/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2224/// or 64-bit immediate, and if the value can be accurately represented as a
2225/// sign extension from a 16-bit value. If so, this returns true and the
2226/// immediate.
2227bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2228 if (!isa<ConstantSDNode>(N))
2229 return false;
2230
2231 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2232 if (N->getValueType(0) == MVT::i32)
2233 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2234 else
2235 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2236}
2237bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2238 return isIntS16Immediate(Op.getNode(), Imm);
2239}
2240
2241/// SelectAddressRegReg - Given the specified addressed, check to see if it
2242/// can be represented as an indexed [r+r] operation. Returns false if it
2243/// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2244/// non-zero and N can be represented by a base register plus a signed 16-bit
2245/// displacement, make a more precise judgement by checking (displacement % \p
2246/// EncodingAlignment).
2247bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2248 SDValue &Index, SelectionDAG &DAG,
2249 unsigned EncodingAlignment) const {
2250 int16_t imm = 0;
2251 if (N.getOpcode() == ISD::ADD) {
2252 if (isIntS16Immediate(N.getOperand(1), imm) &&
2253 (!EncodingAlignment || !(imm % EncodingAlignment)))
2254 return false; // r+i
2255 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2256 return false; // r+i
2257
2258 Base = N.getOperand(0);
2259 Index = N.getOperand(1);
2260 return true;
2261 } else if (N.getOpcode() == ISD::OR) {
2262 if (isIntS16Immediate(N.getOperand(1), imm) &&
2263 (!EncodingAlignment || !(imm % EncodingAlignment)))
2264 return false; // r+i can fold it if we can.
2265
2266 // If this is an or of disjoint bitfields, we can codegen this as an add
2267 // (for better address arithmetic) if the LHS and RHS of the OR are provably
2268 // disjoint.
2269 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2270
2271 if (LHSKnown.Zero.getBoolValue()) {
2272 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2273 // If all of the bits are known zero on the LHS or RHS, the add won't
2274 // carry.
2275 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2276 Base = N.getOperand(0);
2277 Index = N.getOperand(1);
2278 return true;
2279 }
2280 }
2281 }
2282
2283 return false;
2284}
2285
2286// If we happen to be doing an i64 load or store into a stack slot that has
2287// less than a 4-byte alignment, then the frame-index elimination may need to
2288// use an indexed load or store instruction (because the offset may not be a
2289// multiple of 4). The extra register needed to hold the offset comes from the
2290// register scavenger, and it is possible that the scavenger will need to use
2291// an emergency spill slot. As a result, we need to make sure that a spill slot
2292// is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2293// stack slot.
2294static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2295 // FIXME: This does not handle the LWA case.
2296 if (VT != MVT::i64)
2297 return;
2298
2299 // NOTE: We'll exclude negative FIs here, which come from argument
2300 // lowering, because there are no known test cases triggering this problem
2301 // using packed structures (or similar). We can remove this exclusion if
2302 // we find such a test case. The reason why this is so test-case driven is
2303 // because this entire 'fixup' is only to prevent crashes (from the
2304 // register scavenger) on not-really-valid inputs. For example, if we have:
2305 // %a = alloca i1
2306 // %b = bitcast i1* %a to i64*
2307 // store i64* a, i64 b
2308 // then the store should really be marked as 'align 1', but is not. If it
2309 // were marked as 'align 1' then the indexed form would have been
2310 // instruction-selected initially, and the problem this 'fixup' is preventing
2311 // won't happen regardless.
2312 if (FrameIdx < 0)
2313 return;
2314
2315 MachineFunction &MF = DAG.getMachineFunction();
2316 MachineFrameInfo &MFI = MF.getFrameInfo();
2317
2318 unsigned Align = MFI.getObjectAlignment(FrameIdx);
2319 if (Align >= 4)
2320 return;
2321
2322 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2323 FuncInfo->setHasNonRISpills();
2324}
2325
2326/// Returns true if the address N can be represented by a base register plus
2327/// a signed 16-bit displacement [r+imm], and if it is not better
2328/// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2329/// displacements that are multiples of that value.
2330bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2331 SDValue &Base,
2332 SelectionDAG &DAG,
2333 unsigned EncodingAlignment) const {
2334 // FIXME dl should come from parent load or store, not from address
2335 SDLoc dl(N);
2336 // If this can be more profitably realized as r+r, fail.
2337 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2338 return false;
2339
2340 if (N.getOpcode() == ISD::ADD) {
2341 int16_t imm = 0;
2342 if (isIntS16Immediate(N.getOperand(1), imm) &&
2343 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2344 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2345 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2346 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2347 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2348 } else {
2349 Base = N.getOperand(0);
2350 }
2351 return true; // [r+i]
2352 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2353 // Match LOAD (ADD (X, Lo(G))).
2354 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2355 && "Cannot handle constant offsets yet!");
2356 Disp = N.getOperand(1).getOperand(0); // The global address.
2357 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2358 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2359 Disp.getOpcode() == ISD::TargetConstantPool ||
2360 Disp.getOpcode() == ISD::TargetJumpTable);
2361 Base = N.getOperand(0);
2362 return true; // [&g+r]
2363 }
2364 } else if (N.getOpcode() == ISD::OR) {
2365 int16_t imm = 0;
2366 if (isIntS16Immediate(N.getOperand(1), imm) &&
2367 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2368 // If this is an or of disjoint bitfields, we can codegen this as an add
2369 // (for better address arithmetic) if the LHS and RHS of the OR are
2370 // provably disjoint.
2371 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2372
2373 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2374 // If all of the bits are known zero on the LHS or RHS, the add won't
2375 // carry.
2376 if (FrameIndexSDNode *FI =
2377 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2378 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2379 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2380 } else {
2381 Base = N.getOperand(0);
2382 }
2383 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2384 return true;
2385 }
2386 }
2387 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2388 // Loading from a constant address.
2389
2390 // If this address fits entirely in a 16-bit sext immediate field, codegen
2391 // this as "d, 0"
2392 int16_t Imm;
2393 if (isIntS16Immediate(CN, Imm) &&
2394 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2395 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2396 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2397 CN->getValueType(0));
2398 return true;
2399 }
2400
2401 // Handle 32-bit sext immediates with LIS + addr mode.
2402 if ((CN->getValueType(0) == MVT::i32 ||
2403 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2404 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2405 int Addr = (int)CN->getZExtValue();
2406
2407 // Otherwise, break this down into an LIS + disp.
2408 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2409
2410 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2411 MVT::i32);
2412 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2413 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2414 return true;
2415 }
2416 }
2417
2418 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2419 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2420 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2421 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2422 } else
2423 Base = N;
2424 return true; // [r+0]
2425}
2426
2427/// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2428/// represented as an indexed [r+r] operation.
2429bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2430 SDValue &Index,
2431 SelectionDAG &DAG) const {
2432 // Check to see if we can easily represent this as an [r+r] address. This
2433 // will fail if it thinks that the address is more profitably represented as
2434 // reg+imm, e.g. where imm = 0.
2435 if (SelectAddressRegReg(N, Base, Index, DAG))
2436 return true;
2437
2438 // If the address is the result of an add, we will utilize the fact that the
2439 // address calculation includes an implicit add. However, we can reduce
2440 // register pressure if we do not materialize a constant just for use as the
2441 // index register. We only get rid of the add if it is not an add of a
2442 // value and a 16-bit signed constant and both have a single use.
2443 int16_t imm = 0;
2444 if (N.getOpcode() == ISD::ADD &&
2445 (!isIntS16Immediate(N.getOperand(1), imm) ||
2446 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2447 Base = N.getOperand(0);
2448 Index = N.getOperand(1);
2449 return true;
2450 }
2451
2452 // Otherwise, do it the hard way, using R0 as the base register.
2453 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2454 N.getValueType());
2455 Index = N;
2456 return true;
2457}
2458
2459/// Returns true if we should use a direct load into vector instruction
2460/// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2461static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2462
2463 // If there are any other uses other than scalar to vector, then we should
2464 // keep it as a scalar load -> direct move pattern to prevent multiple
2465 // loads.
2466 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2467 if (!LD)
2468 return false;
2469
2470 EVT MemVT = LD->getMemoryVT();
2471 if (!MemVT.isSimple())
2472 return false;
2473 switch(MemVT.getSimpleVT().SimpleTy) {
2474 case MVT::i64:
2475 break;
2476 case MVT::i32:
2477 if (!ST.hasP8Vector())
2478 return false;
2479 break;
2480 case MVT::i16:
2481 case MVT::i8:
2482 if (!ST.hasP9Vector())
2483 return false;
2484 break;
2485 default:
2486 return false;
2487 }
2488
2489 SDValue LoadedVal(N, 0);
2490 if (!LoadedVal.hasOneUse())
2491 return false;
2492
2493 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2494 UI != UE; ++UI)
2495 if (UI.getUse().get().getResNo() == 0 &&
2496 UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2497 return false;
2498
2499 return true;
2500}
2501
2502/// getPreIndexedAddressParts - returns true by value, base pointer and
2503/// offset pointer and addressing mode by reference if the node's address
2504/// can be legally represented as pre-indexed load / store address.
2505bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2506 SDValue &Offset,
2507 ISD::MemIndexedMode &AM,
2508 SelectionDAG &DAG) const {
2509 if (DisablePPCPreinc) return false;
2510
2511 bool isLoad = true;
2512 SDValue Ptr;
2513 EVT VT;
2514 unsigned Alignment;
2515 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2516 Ptr = LD->getBasePtr();
2517 VT = LD->getMemoryVT();
2518 Alignment = LD->getAlignment();
2519 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2520 Ptr = ST->getBasePtr();
2521 VT = ST->getMemoryVT();
2522 Alignment = ST->getAlignment();
2523 isLoad = false;
2524 } else
2525 return false;
2526
2527 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2528 // instructions because we can fold these into a more efficient instruction
2529 // instead, (such as LXSD).
2530 if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2531 return false;
2532 }
2533
2534 // PowerPC doesn't have preinc load/store instructions for vectors (except
2535 // for QPX, which does have preinc r+r forms).
2536 if (VT.isVector()) {
2537 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2538 return false;
2539 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2540 AM = ISD::PRE_INC;
2541 return true;
2542 }
2543 }
2544
2545 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2546 // Common code will reject creating a pre-inc form if the base pointer
2547 // is a frame index, or if N is a store and the base pointer is either
2548 // the same as or a predecessor of the value being stored. Check for
2549 // those situations here, and try with swapped Base/Offset instead.
2550 bool Swap = false;
2551
2552 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2553 Swap = true;
2554 else if (!isLoad) {
2555 SDValue Val = cast<StoreSDNode>(N)->getValue();
2556 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2557 Swap = true;
2558 }
2559
2560 if (Swap)
2561 std::swap(Base, Offset);
2562
2563 AM = ISD::PRE_INC;
2564 return true;
2565 }
2566
2567 // LDU/STU can only handle immediates that are a multiple of 4.
2568 if (VT != MVT::i64) {
2569 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2570 return false;
2571 } else {
2572 // LDU/STU need an address with at least 4-byte alignment.
2573 if (Alignment < 4)
2574 return false;
2575
2576 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2577 return false;
2578 }
2579
2580 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2581 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2582 // sext i32 to i64 when addr mode is r+i.
2583 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2584 LD->getExtensionType() == ISD::SEXTLOAD &&
2585 isa<ConstantSDNode>(Offset))
2586 return false;
2587 }
2588
2589 AM = ISD::PRE_INC;
2590 return true;
2591}
2592
2593//===----------------------------------------------------------------------===//
2594// LowerOperation implementation
2595//===----------------------------------------------------------------------===//
2596
2597/// Return true if we should reference labels using a PICBase, set the HiOpFlags
2598/// and LoOpFlags to the target MO flags.
2599static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2600 unsigned &HiOpFlags, unsigned &LoOpFlags,
2601 const GlobalValue *GV = nullptr) {
2602 HiOpFlags = PPCII::MO_HA;
2603 LoOpFlags = PPCII::MO_LO;
2604
2605 // Don't use the pic base if not in PIC relocation model.
2606 if (IsPIC) {
2607 HiOpFlags |= PPCII::MO_PIC_FLAG;
2608 LoOpFlags |= PPCII::MO_PIC_FLAG;
2609 }
2610
2611 // If this is a reference to a global value that requires a non-lazy-ptr, make
2612 // sure that instruction lowering adds it.
2613 if (GV && Subtarget.hasLazyResolverStub(GV)) {
2614 HiOpFlags |= PPCII::MO_NLP_FLAG;
2615 LoOpFlags |= PPCII::MO_NLP_FLAG;
2616
2617 if (GV->hasHiddenVisibility()) {
2618 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2619 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2620 }
2621 }
2622}
2623
2624static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2625 SelectionDAG &DAG) {
2626 SDLoc DL(HiPart);
2627 EVT PtrVT = HiPart.getValueType();
2628 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2629
2630 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2631 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2632
2633 // With PIC, the first instruction is actually "GR+hi(&G)".
2634 if (isPIC)
2635 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2636 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2637
2638 // Generate non-pic code that has direct accesses to the constant pool.
2639 // The address of the global is just (hi(&g)+lo(&g)).
2640 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2641}
2642
2643static void setUsesTOCBasePtr(MachineFunction &MF) {
2644 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2645 FuncInfo->setUsesTOCBasePtr();
2646}
2647
2648static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2649 setUsesTOCBasePtr(DAG.getMachineFunction());
2650}
2651
2652static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2653 SDValue GA) {
2654 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2655 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2656 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2657
2658 SDValue Ops[] = { GA, Reg };
2659 return DAG.getMemIntrinsicNode(
2660 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2661 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2662 MachineMemOperand::MOLoad);
2663}
2664
2665SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2666 SelectionDAG &DAG) const {
2667 EVT PtrVT = Op.getValueType();
2668 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2669 const Constant *C = CP->getConstVal();
2670
2671 // 64-bit SVR4 ABI code is always position-independent.
2672 // The actual address of the GlobalValue is stored in the TOC.
2673 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2674 setUsesTOCBasePtr(DAG);
2675 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2676 return getTOCEntry(DAG, SDLoc(CP), true, GA);
2677 }
2678
2679 unsigned MOHiFlag, MOLoFlag;
2680 bool IsPIC = isPositionIndependent();
2681 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2682
2683 if (IsPIC && Subtarget.isSVR4ABI()) {
2684 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2685 PPCII::MO_PIC_FLAG);
2686 return getTOCEntry(DAG, SDLoc(CP), false, GA);
2687 }
2688
2689 SDValue CPIHi =
2690 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2691 SDValue CPILo =
2692 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2693 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2694}
2695
2696// For 64-bit PowerPC, prefer the more compact relative encodings.
2697// This trades 32 bits per jump table entry for one or two instructions
2698// on the jump site.
2699unsigned PPCTargetLowering::getJumpTableEncoding() const {
2700 if (isJumpTableRelative())
2701 return MachineJumpTableInfo::EK_LabelDifference32;
2702
2703 return TargetLowering::getJumpTableEncoding();
2704}
2705
2706bool PPCTargetLowering::isJumpTableRelative() const {
2707 if (Subtarget.isPPC64())
2708 return true;
2709 return TargetLowering::isJumpTableRelative();
2710}
2711
2712SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2713 SelectionDAG &DAG) const {
2714 if (!Subtarget.isPPC64())
2715 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2716
2717 switch (getTargetMachine().getCodeModel()) {
2718 case CodeModel::Small:
2719 case CodeModel::Medium:
2720 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2721 default:
2722 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2723 getPointerTy(DAG.getDataLayout()));
2724 }
2725}
2726
2727const MCExpr *
2728PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2729 unsigned JTI,
2730 MCContext &Ctx) const {
2731 if (!Subtarget.isPPC64())
2732 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2733
2734 switch (getTargetMachine().getCodeModel()) {
2735 case CodeModel::Small:
2736 case CodeModel::Medium:
2737 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2738 default:
2739 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2740 }
2741}
2742
2743SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2744 EVT PtrVT = Op.getValueType();
2745 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2746
2747 // 64-bit SVR4 ABI code is always position-independent.
2748 // The actual address of the GlobalValue is stored in the TOC.
2749 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2750 setUsesTOCBasePtr(DAG);
2751 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2752 return getTOCEntry(DAG, SDLoc(JT), true, GA);
2753 }
2754
2755 unsigned MOHiFlag, MOLoFlag;
2756 bool IsPIC = isPositionIndependent();
2757 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2758
2759 if (IsPIC && Subtarget.isSVR4ABI()) {
2760 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2761 PPCII::MO_PIC_FLAG);
2762 return getTOCEntry(DAG, SDLoc(GA), false, GA);
2763 }
2764
2765 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2766 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2767 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2768}
2769
2770SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2771 SelectionDAG &DAG) const {
2772 EVT PtrVT = Op.getValueType();
2773 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2774 const BlockAddress *BA = BASDN->getBlockAddress();
2775
2776 // 64-bit SVR4 ABI code is always position-independent.
2777 // The actual BlockAddress is stored in the TOC.
2778 if (Subtarget.isSVR4ABI() &&
2779 (Subtarget.isPPC64() || isPositionIndependent())) {
2780 if (Subtarget.isPPC64())
2781 setUsesTOCBasePtr(DAG);
2782 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2783 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA);
2784 }
2785
2786 unsigned MOHiFlag, MOLoFlag;
2787 bool IsPIC = isPositionIndependent();
2788 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2789 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2790 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2791 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2792}
2793
2794SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2795 SelectionDAG &DAG) const {
2796 // FIXME: TLS addresses currently use medium model code sequences,
2797 // which is the most useful form. Eventually support for small and
2798 // large models could be added if users need it, at the cost of
2799 // additional complexity.
2800 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2801 if (DAG.getTarget().useEmulatedTLS())
2802 return LowerToTLSEmulatedModel(GA, DAG);
2803
2804 SDLoc dl(GA);
2805 const GlobalValue *GV = GA->getGlobal();
2806 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2807 bool is64bit = Subtarget.isPPC64();
2808 const Module *M = DAG.getMachineFunction().getFunction().getParent();
2809 PICLevel::Level picLevel = M->getPICLevel();
2810
2811 const TargetMachine &TM = getTargetMachine();
2812 TLSModel::Model Model = TM.getTLSModel(GV);
2813
2814 if (Model == TLSModel::LocalExec) {
2815 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2816 PPCII::MO_TPREL_HA);
2817 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2818 PPCII::MO_TPREL_LO);
2819 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2820 : DAG.getRegister(PPC::R2, MVT::i32);
2821
2822 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2823 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2824 }
2825
2826 if (Model == TLSModel::InitialExec) {
2827 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2828 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2829 PPCII::MO_TLS);
2830 SDValue GOTPtr;
2831 if (is64bit) {
2832 setUsesTOCBasePtr(DAG);
2833 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2834 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2835 PtrVT, GOTReg, TGA);
2836 } else {
2837 if (!TM.isPositionIndependent())
2838 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2839 else if (picLevel == PICLevel::SmallPIC)
2840 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2841 else
2842 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2843 }
2844 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2845 PtrVT, TGA, GOTPtr);
2846 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2847 }
2848
2849 if (Model == TLSModel::GeneralDynamic) {
2850 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2851 SDValue GOTPtr;
2852 if (is64bit) {
2853 setUsesTOCBasePtr(DAG);
2854 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2855 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2856 GOTReg, TGA);
2857 } else {
2858 if (picLevel == PICLevel::SmallPIC)
2859 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2860 else
2861 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2862 }
2863 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2864 GOTPtr, TGA, TGA);
2865 }
2866
2867 if (Model == TLSModel::LocalDynamic) {
2868 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2869 SDValue GOTPtr;
2870 if (is64bit) {
2871 setUsesTOCBasePtr(DAG);
2872 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2873 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2874 GOTReg, TGA);
2875 } else {
2876 if (picLevel == PICLevel::SmallPIC)
2877 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2878 else
2879 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2880 }
2881 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2882 PtrVT, GOTPtr, TGA, TGA);
2883 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2884 PtrVT, TLSAddr, TGA);
2885 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2886 }
2887
2888 llvm_unreachable("Unknown TLS model!");
2889}
2890
2891SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2892 SelectionDAG &DAG) const {
2893 EVT PtrVT = Op.getValueType();
2894 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2895 SDLoc DL(GSDN);
2896 const GlobalValue *GV = GSDN->getGlobal();
2897
2898 // 64-bit SVR4 ABI code is always position-independent.
2899 // The actual address of the GlobalValue is stored in the TOC.
2900 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2901 setUsesTOCBasePtr(DAG);
2902 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2903 return getTOCEntry(DAG, DL, true, GA);
2904 }
2905
2906 unsigned MOHiFlag, MOLoFlag;
2907 bool IsPIC = isPositionIndependent();
2908 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2909
2910 if (IsPIC && Subtarget.isSVR4ABI()) {
2911 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2912 GSDN->getOffset(),
2913 PPCII::MO_PIC_FLAG);
2914 return getTOCEntry(DAG, DL, false, GA);
2915 }
2916
2917 SDValue GAHi =
2918 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2919 SDValue GALo =
2920 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2921
2922 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2923
2924 // If the global reference is actually to a non-lazy-pointer, we have to do an
2925 // extra load to get the address of the global.
2926 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2927 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2928 return Ptr;
2929}
2930
2931SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2932 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2933 SDLoc dl(Op);
2934
2935 if (Op.getValueType() == MVT::v2i64) {
2936 // When the operands themselves are v2i64 values, we need to do something
2937 // special because VSX has no underlying comparison operations for these.
2938 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2939 // Equality can be handled by casting to the legal type for Altivec
2940 // comparisons, everything else needs to be expanded.
2941 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2942 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2943 DAG.getSetCC(dl, MVT::v4i32,
2944 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2945 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2946 CC));
2947 }
2948
2949 return SDValue();
2950 }
2951
2952 // We handle most of these in the usual way.
2953 return Op;
2954 }
2955
2956 // If we're comparing for equality to zero, expose the fact that this is
2957 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2958 // fold the new nodes.
2959 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2960 return V;
2961
2962 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2963 // Leave comparisons against 0 and -1 alone for now, since they're usually
2964 // optimized. FIXME: revisit this when we can custom lower all setcc
2965 // optimizations.
2966 if (C->isAllOnesValue() || C->isNullValue())
2967 return SDValue();
2968 }
2969
2970 // If we have an integer seteq/setne, turn it into a compare against zero
2971 // by xor'ing the rhs with the lhs, which is faster than setting a
2972 // condition register, reading it back out, and masking the correct bit. The
2973 // normal approach here uses sub to do this instead of xor. Using xor exposes
2974 // the result to other bit-twiddling opportunities.
2975 EVT LHSVT = Op.getOperand(0).getValueType();
2976 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2977 EVT VT = Op.getValueType();
2978 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2979 Op.getOperand(1));
2980 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2981 }
2982 return SDValue();
2983}
2984
2985SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2986 SDNode *Node = Op.getNode();
2987 EVT VT = Node->getValueType(0);
2988 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2989 SDValue InChain = Node->getOperand(0);
2990 SDValue VAListPtr = Node->getOperand(1);
2991 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2992 SDLoc dl(Node);
2993
2994 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2995
2996 // gpr_index
2997 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2998 VAListPtr, MachinePointerInfo(SV), MVT::i8);
2999 InChain = GprIndex.getValue(1);
3000
3001 if (VT == MVT::i64) {
3002 // Check if GprIndex is even
3003 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3004 DAG.getConstant(1, dl, MVT::i32));
3005 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3006 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3007 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3008 DAG.getConstant(1, dl, MVT::i32));
3009 // Align GprIndex to be even if it isn't
3010 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3011 GprIndex);
3012 }
3013
3014 // fpr index is 1 byte after gpr
3015 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3016 DAG.getConstant(1, dl, MVT::i32));
3017
3018 // fpr
3019 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3020 FprPtr, MachinePointerInfo(SV), MVT::i8);
3021 InChain = FprIndex.getValue(1);
3022
3023 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3024 DAG.getConstant(8, dl, MVT::i32));
3025
3026 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3027 DAG.getConstant(4, dl, MVT::i32));
3028
3029 // areas
3030 SDValue OverflowArea =
3031 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3032 InChain = OverflowArea.getValue(1);
3033
3034 SDValue RegSaveArea =
3035 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3036 InChain = RegSaveArea.getValue(1);
3037
3038 // select overflow_area if index > 8
3039 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3040 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3041
3042 // adjustment constant gpr_index * 4/8
3043 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3044 VT.isInteger() ? GprIndex : FprIndex,
3045 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3046 MVT::i32));
3047
3048 // OurReg = RegSaveArea + RegConstant
3049 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3050 RegConstant);
3051
3052 // Floating types are 32 bytes into RegSaveArea
3053 if (VT.isFloatingPoint())
3054 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3055 DAG.getConstant(32, dl, MVT::i32));
3056
3057 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3058 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3059 VT.isInteger() ? GprIndex : FprIndex,
3060 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3061 MVT::i32));
3062
3063 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3064 VT.isInteger() ? VAListPtr : FprPtr,
3065 MachinePointerInfo(SV), MVT::i8);
3066
3067 // determine if we should load from reg_save_area or overflow_area
3068 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3069
3070 // increase overflow_area by 4/8 if gpr/fpr > 8
3071 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3072 DAG.getConstant(VT.isInteger() ? 4 : 8,
3073 dl, MVT::i32));
3074
3075 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3076 OverflowAreaPlusN);
3077
3078 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3079 MachinePointerInfo(), MVT::i32);
3080
3081 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3082}
3083
3084SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3085 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3086
3087 // We have to copy the entire va_list struct:
3088 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3089 return DAG.getMemcpy(Op.getOperand(0), Op,
3090 Op.getOperand(1), Op.getOperand(2),
3091 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3092 false, false, MachinePointerInfo(), MachinePointerInfo());
3093}
3094
3095SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3096 SelectionDAG &DAG) const {
3097 return Op.getOperand(0);
3098}
3099
3100SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3101 SelectionDAG &DAG) const {
3102 SDValue Chain = Op.getOperand(0);
3103 SDValue Trmp = Op.getOperand(1); // trampoline
3104 SDValue FPtr = Op.getOperand(2); // nested function
3105 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3106 SDLoc dl(Op);
3107
3108 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3109 bool isPPC64 = (PtrVT == MVT::i64);
3110 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3111
3112 TargetLowering::ArgListTy Args;
3113 TargetLowering::ArgListEntry Entry;
3114
3115 Entry.Ty = IntPtrTy;
3116 Entry.Node = Trmp; Args.push_back(Entry);
3117
3118 // TrampSize == (isPPC64 ? 48 : 40);
3119 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3120 isPPC64 ? MVT::i64 : MVT::i32);
3121 Args.push_back(Entry);
3122
3123 Entry.Node = FPtr; Args.push_back(Entry);
3124 Entry.Node = Nest; Args.push_back(Entry);
3125
3126 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3127 TargetLowering::CallLoweringInfo CLI(DAG);
3128 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3129 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3130 DAG.getExternalFunctionSymbol("__trampoline_setup"), std::move(Args));
3131
3132 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3133 return CallResult.second;
3134}
3135
3136SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3137 MachineFunction &MF = DAG.getMachineFunction();
3138 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3139 EVT PtrVT = getPointerTy(MF.getDataLayout());
3140
3141 SDLoc dl(Op);
3142
3143 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3144 // vastart just stores the address of the VarArgsFrameIndex slot into the
3145 // memory location argument.
3146 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3147 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3148 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3149 MachinePointerInfo(SV));
3150 }
3151
3152 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3153 // We suppose the given va_list is already allocated.
3154 //
3155 // typedef struct {
3156 // char gpr; /* index into the array of 8 GPRs
3157 // * stored in the register save area
3158 // * gpr=0 corresponds to r3,
3159 // * gpr=1 to r4, etc.
3160 // */
3161 // char fpr; /* index into the array of 8 FPRs
3162 // * stored in the register save area
3163 // * fpr=0 corresponds to f1,
3164 // * fpr=1 to f2, etc.
3165 // */
3166 // char *overflow_arg_area;
3167 // /* location on stack that holds
3168 // * the next overflow argument
3169 // */
3170 // char *reg_save_area;
3171 // /* where r3:r10 and f1:f8 (if saved)
3172 // * are stored
3173 // */
3174 // } va_list[1];
3175
3176 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3177 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3178 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3179 PtrVT);
3180 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3181 PtrVT);
3182
3183 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3184 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3185
3186 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3187 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3188
3189 uint64_t FPROffset = 1;
3190 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3191
3192 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3193
3194 // Store first byte : number of int regs
3195 SDValue firstStore =
3196 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3197 MachinePointerInfo(SV), MVT::i8);
3198 uint64_t nextOffset = FPROffset;
3199 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3200 ConstFPROffset);
3201
3202 // Store second byte : number of float regs
3203 SDValue secondStore =
3204 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3205 MachinePointerInfo(SV, nextOffset), MVT::i8);
3206 nextOffset += StackOffset;
3207 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3208
3209 // Store second word : arguments given on stack
3210 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3211 MachinePointerInfo(SV, nextOffset));
3212 nextOffset += FrameOffset;
3213 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3214
3215 // Store third word : arguments given in registers
3216 return DAG.getStore(thirdStore, dl, FR, nextPtr,
3217 MachinePointerInfo(SV, nextOffset));
3218}
3219
3220/// FPR - The set of FP registers that should be allocated for arguments,
3221/// on Darwin.
3222static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
3223 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
3224 PPC::F11, PPC::F12, PPC::F13};
3225
3226/// QFPR - The set of QPX registers that should be allocated for arguments.
3227static const MCPhysReg QFPR[] = {
3228 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
3229 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3230
3231/// CalculateStackSlotSize - Calculates the size reserved for this argument on
3232/// the stack.
3233static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3234 unsigned PtrByteSize) {
3235 unsigned ArgSize = ArgVT.getStoreSize();
3236 if (Flags.isByVal())
3237 ArgSize = Flags.getByValSize();
3238
3239 // Round up to multiples of the pointer size, except for array members,
3240 // which are always packed.
3241 if (!Flags.isInConsecutiveRegs())
3242 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3243
3244 return ArgSize;
3245}
3246
3247/// CalculateStackSlotAlignment - Calculates the alignment of this argument
3248/// on the stack.
3249static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3250 ISD::ArgFlagsTy Flags,
3251 unsigned PtrByteSize) {
3252 unsigned Align = PtrByteSize;
3253
3254 // Altivec parameters are padded to a 16 byte boundary.
3255 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3256 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3257 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3258 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3259 Align = 16;
3260 // QPX vector types stored in double-precision are padded to a 32 byte
3261 // boundary.
3262 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3263 Align = 32;
3264
3265 // ByVal parameters are aligned as requested.
3266 if (Flags.isByVal()) {
3267 unsigned BVAlign = Flags.getByValAlign();
3268 if (BVAlign > PtrByteSize) {
3269 if (BVAlign % PtrByteSize != 0)
3270 llvm_unreachable(
3271 "ByVal alignment is not a multiple of the pointer size");
3272
3273 Align = BVAlign;
3274 }
3275 }
3276
3277 // Array members are always packed to their original alignment.
3278 if (Flags.isInConsecutiveRegs()) {
3279 // If the array member was split into multiple registers, the first
3280 // needs to be aligned to the size of the full type. (Except for
3281 // ppcf128, which is only aligned as its f64 components.)
3282 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3283 Align = OrigVT.getStoreSize();
3284 else
3285 Align = ArgVT.getStoreSize();
3286 }
3287
3288 return Align;
3289}
3290
3291/// CalculateStackSlotUsed - Return whether this argument will use its
3292/// stack slot (instead of being passed in registers). ArgOffset,
3293/// AvailableFPRs, and AvailableVRs must hold the current argument
3294/// position, and will be updated to account for this argument.
3295static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3296 ISD::ArgFlagsTy Flags,
3297 unsigned PtrByteSize,
3298 unsigned LinkageSize,
3299 unsigned ParamAreaSize,
3300 unsigned &ArgOffset,
3301 unsigned &AvailableFPRs,
3302 unsigned &AvailableVRs, bool HasQPX) {
3303 bool UseMemory = false;
3304
3305 // Respect alignment of argument on the stack.
3306 unsigned Align =
3307 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3308 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3309 // If there's no space left in the argument save area, we must
3310 // use memory (this check also catches zero-sized arguments).
3311 if (ArgOffset >= LinkageSize + ParamAreaSize)
3312 UseMemory = true;
3313
3314 // Allocate argument on the stack.
3315 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3316 if (Flags.isInConsecutiveRegsLast())
3317 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3318 // If we overran the argument save area, we must use memory
3319 // (this check catches arguments passed partially in memory)
3320 if (ArgOffset > LinkageSize + ParamAreaSize)
3321 UseMemory = true;
3322
3323 // However, if the argument is actually passed in an FPR or a VR,
3324 // we don't use memory after all.
3325 if (!Flags.isByVal()) {
3326 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3327 // QPX registers overlap with the scalar FP registers.
3328 (HasQPX && (ArgVT == MVT::v4f32 ||
3329 ArgVT == MVT::v4f64 ||
3330 ArgVT == MVT::v4i1)))
3331 if (AvailableFPRs > 0) {
3332 --AvailableFPRs;
3333 return false;
3334 }
3335 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3336 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3337 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3338 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3339 if (AvailableVRs > 0) {
3340 --AvailableVRs;
3341 return false;
3342 }
3343 }
3344
3345 return UseMemory;
3346}
3347
3348/// EnsureStackAlignment - Round stack frame size up from NumBytes to
3349/// ensure minimum alignment required for target.
3350static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3351 unsigned NumBytes) {
3352 unsigned TargetAlign = Lowering->getStackAlignment();
3353 unsigned AlignMask = TargetAlign - 1;
3354 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3355 return NumBytes;
3356}
3357
3358SDValue PPCTargetLowering::LowerFormalArguments(
3359 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3360 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3361 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3362 if (Subtarget.isSVR4ABI()) {
3363 if (Subtarget.isPPC64())
3364 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3365 dl, DAG, InVals);
3366 else
3367 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3368 dl, DAG, InVals);
3369 } else {
3370 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3371 dl, DAG, InVals);
3372 }
3373}
3374
3375SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3376 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3377 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3378 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3379
3380 // 32-bit SVR4 ABI Stack Frame Layout:
3381 // +-----------------------------------+
3382 // +--> | Back chain |
3383 // | +-----------------------------------+
3384 // | | Floating-point register save area |
3385 // | +-----------------------------------+
3386 // | | General register save area |
3387 // | +-----------------------------------+
3388 // | | CR save word |
3389 // | +-----------------------------------+
3390 // | | VRSAVE save word |
3391 // | +-----------------------------------+
3392 // | | Alignment padding |
3393 // | +-----------------------------------+
3394 // | | Vector register save area |
3395 // | +-----------------------------------+
3396 // | | Local variable space |
3397 // | +-----------------------------------+
3398 // | | Parameter list area |
3399 // | +-----------------------------------+
3400 // | | LR save word |
3401 // | +-----------------------------------+
3402 // SP--> +--- | Back chain |
3403 // +-----------------------------------+
3404 //
3405 // Specifications:
3406 // System V Application Binary Interface PowerPC Processor Supplement
3407 // AltiVec Technology Programming Interface Manual
3408
3409 MachineFunction &MF = DAG.getMachineFunction();
3410 MachineFrameInfo &MFI = MF.getFrameInfo();
3411 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3412
3413 EVT PtrVT = getPointerTy(MF.getDataLayout());
3414 // Potential tail calls could cause overwriting of argument stack slots.
3415 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3416 (CallConv == CallingConv::Fast));
3417 unsigned PtrByteSize = 4;
3418
3419 // Assign locations to all of the incoming arguments.
3420 SmallVector<CCValAssign, 16> ArgLocs;
3421 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3422 *DAG.getContext());
3423
3424 // Reserve space for the linkage area on the stack.
3425 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3426 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3427 if (useSoftFloat() || hasSPE())
3428 CCInfo.PreAnalyzeFormalArguments(Ins);
3429
3430 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3431 CCInfo.clearWasPPCF128();
3432
3433 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3434 CCValAssign &VA = ArgLocs[i];
3435
3436 // Arguments stored in registers.
3437 if (VA.isRegLoc()) {
3438 const TargetRegisterClass *RC;
3439 EVT ValVT = VA.getValVT();
3440
3441 switch (ValVT.getSimpleVT().SimpleTy) {
3442 default:
3443 llvm_unreachable("ValVT not supported by formal arguments Lowering");
3444 case MVT::i1:
3445 case MVT::i32:
3446 RC = &PPC::GPRCRegClass;
3447 break;
3448 case MVT::f32:
3449 if (Subtarget.hasP8Vector())
3450 RC = &PPC::VSSRCRegClass;
3451 else if (Subtarget.hasSPE())
3452 RC = &PPC::SPE4RCRegClass;
3453 else
3454 RC = &PPC::F4RCRegClass;
3455 break;
3456 case MVT::f64:
3457 if (Subtarget.hasVSX())
3458 RC = &PPC::VSFRCRegClass;
3459 else if (Subtarget.hasSPE())
3460 RC = &PPC::SPERCRegClass;
3461 else
3462 RC = &PPC::F8RCRegClass;
3463 break;
3464 case MVT::v16i8:
3465 case MVT::v8i16:
3466 case MVT::v4i32:
3467 RC = &PPC::VRRCRegClass;
3468 break;
3469 case MVT::v4f32:
3470 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3471 break;
3472 case MVT::v2f64:
3473 case MVT::v2i64:
3474 RC = &PPC::VRRCRegClass;
3475 break;
3476 case MVT::v4f64:
3477 RC = &PPC::QFRCRegClass;
3478 break;
3479 case MVT::v4i1:
3480 RC = &PPC::QBRCRegClass;
3481 break;
3482 }
3483
3484 // Transform the arguments stored in physical registers into virtual ones.
3485 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3486 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3487 ValVT == MVT::i1 ? MVT::i32 : ValVT);
3488
3489 if (ValVT == MVT::i1)
3490 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3491
3492 InVals.push_back(ArgValue);
3493 } else {
3494 // Argument stored in memory.
3495 assert(VA.isMemLoc());
3496
3497 // Get the extended size of the argument type in stack
3498 unsigned ArgSize = VA.getLocVT().getStoreSize();
3499 // Get the actual size of the argument type
3500 unsigned ObjSize = VA.getValVT().getStoreSize();
3501 unsigned ArgOffset = VA.getLocMemOffset();
3502 // Stack objects in PPC32 are right justified.
3503 ArgOffset += ArgSize - ObjSize;
3504 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3505
3506 // Create load nodes to retrieve arguments from the stack.
3507 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3508 InVals.push_back(
3509 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3510 }
3511 }
3512
3513 // Assign locations to all of the incoming aggregate by value arguments.
3514 // Aggregates passed by value are stored in the local variable space of the
3515 // caller's stack frame, right above the parameter list area.
3516 SmallVector<CCValAssign, 16> ByValArgLocs;
3517 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3518 ByValArgLocs, *DAG.getContext());
3519
3520 // Reserve stack space for the allocations in CCInfo.
3521 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3522
3523 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3524
3525 // Area that is at least reserved in the caller of this function.
3526 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3527 MinReservedArea = std::max(MinReservedArea, LinkageSize);
3528
3529 // Set the size that is at least reserved in caller of this function. Tail
3530 // call optimized function's reserved stack space needs to be aligned so that
3531 // taking the difference between two stack areas will result in an aligned
3532 // stack.
3533 MinReservedArea =
3534 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3535 FuncInfo->setMinReservedArea(MinReservedArea);
3536
3537 SmallVector<SDValue, 8> MemOps;
3538
3539 // If the function takes variable number of arguments, make a frame index for
3540 // the start of the first vararg value... for expansion of llvm.va_start.
3541 if (isVarArg) {
3542 static const MCPhysReg GPArgRegs[] = {
3543 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3544 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3545 };
3546 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3547
3548 static const MCPhysReg FPArgRegs[] = {
3549 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3550 PPC::F8
3551 };
3552 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3553
3554 if (useSoftFloat() || hasSPE())
3555 NumFPArgRegs = 0;
3556
3557 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3558 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3559
3560 // Make room for NumGPArgRegs and NumFPArgRegs.
3561 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3562 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3563
3564 FuncInfo->setVarArgsStackOffset(
3565 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3566 CCInfo.getNextStackOffset(), true));
3567
3568 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3569 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3570
3571 // The fixed integer arguments of a variadic function are stored to the
3572 // VarArgsFrameIndex on the stack so that they may be loaded by
3573 // dereferencing the result of va_next.
3574 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3575 // Get an existing live-in vreg, or add a new one.
3576 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3577 if (!VReg)
3578 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3579
3580 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3581 SDValue Store =
3582 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3583 MemOps.push_back(Store);
3584 // Increment the address by four for the next argument to store
3585 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3586 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3587 }
3588
3589 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3590 // is set.
3591 // The double arguments are stored to the VarArgsFrameIndex
3592 // on the stack.
3593 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3594 // Get an existing live-in vreg, or add a new one.
3595 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3596 if (!VReg)
3597 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3598
3599 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3600 SDValue Store =
3601 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3602 MemOps.push_back(Store);
3603 // Increment the address by eight for the next argument to store
3604 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3605 PtrVT);
3606 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3607 }
3608 }
3609
3610 if (!MemOps.empty())
3611 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3612
3613 return Chain;
3614}
3615
3616// PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3617// value to MVT::i64 and then truncate to the correct register size.
3618SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3619 EVT ObjectVT, SelectionDAG &DAG,
3620 SDValue ArgVal,
3621 const SDLoc &dl) const {
3622 if (Flags.isSExt())
3623 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3624 DAG.getValueType(ObjectVT));
3625 else if (Flags.isZExt())
3626 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3627 DAG.getValueType(ObjectVT));
3628
3629 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3630}
3631
3632SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3633 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3634 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3635 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3636 // TODO: add description of PPC stack frame format, or at least some docs.
3637 //
3638 bool isELFv2ABI = Subtarget.isELFv2ABI();
3639 bool isLittleEndian = Subtarget.isLittleEndian();
3640 MachineFunction &MF = DAG.getMachineFunction();
3641 MachineFrameInfo &MFI = MF.getFrameInfo();
3642 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3643
3644 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3645 "fastcc not supported on varargs functions");
3646
3647 EVT PtrVT = getPointerTy(MF.getDataLayout());
3648 // Potential tail calls could cause overwriting of argument stack slots.
3649 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3650 (CallConv == CallingConv::Fast));
3651 unsigned PtrByteSize = 8;
3652 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3653
3654 static const MCPhysReg GPR[] = {
3655 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3656 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3657 };
3658 static const MCPhysReg VR[] = {
3659 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3660 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3661 };
3662
3663 const unsigned Num_GPR_Regs = array_lengthof(GPR);
3664 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3665 const unsigned Num_VR_Regs = array_lengthof(VR);
3666 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3667
3668 // Do a first pass over the arguments to determine whether the ABI
3669 // guarantees that our caller has allocated the parameter save area
3670 // on its stack frame. In the ELFv1 ABI, this is always the case;
3671 // in the ELFv2 ABI, it is true if this is a vararg function or if
3672 // any parameter is located in a stack slot.
3673
3674 bool HasParameterArea = !isELFv2ABI || isVarArg;
3675 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3676 unsigned NumBytes = LinkageSize;
3677 unsigned AvailableFPRs = Num_FPR_Regs;
3678 unsigned AvailableVRs = Num_VR_Regs;
3679 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3680 if (Ins[i].Flags.isNest())
3681 continue;
3682
3683 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3684 PtrByteSize, LinkageSize, ParamAreaSize,
3685 NumBytes, AvailableFPRs, AvailableVRs,
3686 Subtarget.hasQPX()))
3687 HasParameterArea = true;
3688 }
3689
3690 // Add DAG nodes to load the arguments or copy them out of registers. On
3691 // entry to a function on PPC, the arguments start after the linkage area,
3692 // although the first ones are often in registers.
3693
3694 unsigned ArgOffset = LinkageSize;
3695 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3696 unsigned &QFPR_idx = FPR_idx;
3697 SmallVector<SDValue, 8> MemOps;
3698 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3699 unsigned CurArgIdx = 0;
3700 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3701 SDValue ArgVal;
3702 bool needsLoad = false;
3703 EVT ObjectVT = Ins[ArgNo].VT;
3704 EVT OrigVT = Ins[ArgNo].ArgVT;
3705 unsigned ObjSize = ObjectVT.getStoreSize();
3706 unsigned ArgSize = ObjSize;
3707 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3708 if (Ins[ArgNo].isOrigArg()) {
3709 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3710 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3711 }
3712 // We re-align the argument offset for each argument, except when using the
3713 // fast calling convention, when we need to make sure we do that only when
3714 // we'll actually use a stack slot.
3715 unsigned CurArgOffset, Align;
3716 auto ComputeArgOffset = [&]() {
3717 /* Respect alignment of argument on the stack. */
3718 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3719 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3720 CurArgOffset = ArgOffset;
3721 };
3722
3723 if (CallConv != CallingConv::Fast) {
3724 ComputeArgOffset();
3725
3726 /* Compute GPR index associated with argument offset. */
3727 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3728 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3729 }
3730
3731 // FIXME the codegen can be much improved in some cases.
3732 // We do not have to keep everything in memory.
3733 if (Flags.isByVal()) {
3734 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3735
3736 if (CallConv == CallingConv::Fast)
3737 ComputeArgOffset();
3738
3739 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3740 ObjSize = Flags.getByValSize();
3741 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3742 // Empty aggregate parameters do not take up registers. Examples:
3743 // struct { } a;
3744 // union { } b;
3745 // int c[0];
3746 // etc. However, we have to provide a place-holder in InVals, so
3747 // pretend we have an 8-byte item at the current address for that
3748 // purpose.
3749 if (!ObjSize) {
3750 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3751 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3752 InVals.push_back(FIN);
3753 continue;
3754 }
3755
3756 // Create a stack object covering all stack doublewords occupied
3757 // by the argument. If the argument is (fully or partially) on
3758 // the stack, or if the argument is fully in registers but the
3759 // caller has allocated the parameter save anyway, we can refer
3760 // directly to the caller's stack frame. Otherwise, create a
3761 // local copy in our own frame.
3762 int FI;
3763 if (HasParameterArea ||
3764 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3765 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3766 else
3767 FI = MFI.CreateStackObject(ArgSize, Align, false);
3768 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3769
3770 // Handle aggregates smaller than 8 bytes.
3771 if (ObjSize < PtrByteSize) {
3772 // The value of the object is its address, which differs from the
3773 // address of the enclosing doubleword on big-endian systems.
3774 SDValue Arg = FIN;
3775 if (!isLittleEndian) {
3776 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3777 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3778 }
3779 InVals.push_back(Arg);
3780
3781 if (GPR_idx != Num_GPR_Regs) {
3782 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3783 FuncInfo->addLiveInAttr(VReg, Flags);
3784 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3785 SDValue Store;
3786
3787 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3788 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3789 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3790 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3791 MachinePointerInfo(&*FuncArg), ObjType);
3792 } else {
3793 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3794 // store the whole register as-is to the parameter save area
3795 // slot.
3796 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3797 MachinePointerInfo(&*FuncArg));
3798 }
3799
3800 MemOps.push_back(Store);
3801 }
3802 // Whether we copied from a register or not, advance the offset
3803 // into the parameter save area by a full doubleword.
3804 ArgOffset += PtrByteSize;
3805 continue;
3806 }
3807
3808 // The value of the object is its address, which is the address of
3809 // its first stack doubleword.
3810 InVals.push_back(FIN);
3811
3812 // Store whatever pieces of the object are in registers to memory.
3813 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3814 if (GPR_idx == Num_GPR_Regs)
3815 break;
3816
3817 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3818 FuncInfo->addLiveInAttr(VReg, Flags);
3819 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3820 SDValue Addr = FIN;
3821 if (j) {
3822 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3823 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3824 }
3825 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3826 MachinePointerInfo(&*FuncArg, j));
3827 MemOps.push_back(Store);
3828 ++GPR_idx;
3829 }
3830 ArgOffset += ArgSize;
3831 continue;
3832 }
3833
3834 switch (ObjectVT.getSimpleVT().SimpleTy) {
3835 default: llvm_unreachable("Unhandled argument type!");
3836 case MVT::i1:
3837 case MVT::i32:
3838 case MVT::i64:
3839 if (Flags.isNest()) {
3840 // The 'nest' parameter, if any, is passed in R11.
3841 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3842 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3843
3844 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3845 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3846
3847 break;
3848 }
3849
3850 // These can be scalar arguments or elements of an integer array type
3851 // passed directly. Clang may use those instead of "byval" aggregate
3852 // types to avoid forcing arguments to memory unnecessarily.
3853 if (GPR_idx != Num_GPR_Regs) {
3854 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3855 FuncInfo->addLiveInAttr(VReg, Flags);
3856 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3857
3858 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3859 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3860 // value to MVT::i64 and then truncate to the correct register size.
3861 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3862 } else {
3863 if (CallConv == CallingConv::Fast)
3864 ComputeArgOffset();
3865
3866 needsLoad = true;
3867 ArgSize = PtrByteSize;
3868 }
3869 if (CallConv != CallingConv::Fast || needsLoad)
3870 ArgOffset += 8;
3871 break;
3872
3873 case MVT::f32:
3874 case MVT::f64:
3875 // These can be scalar arguments or elements of a float array type
3876 // passed directly. The latter are used to implement ELFv2 homogenous
3877 // float aggregates.
3878 if (FPR_idx != Num_FPR_Regs) {
3879 unsigned VReg;
3880
3881 if (ObjectVT == MVT::f32)
3882 VReg = MF.addLiveIn(FPR[FPR_idx],
3883 Subtarget.hasP8Vector()
3884 ? &PPC::VSSRCRegClass
3885 : &PPC::F4RCRegClass);
3886 else
3887 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3888 ? &PPC::VSFRCRegClass
3889 : &PPC::F8RCRegClass);
3890
3891 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3892 ++FPR_idx;
3893 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3894 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3895 // once we support fp <-> gpr moves.
3896
3897 // This can only ever happen in the presence of f32 array types,
3898 // since otherwise we never run out of FPRs before running out
3899 // of GPRs.
3900 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3901 FuncInfo->addLiveInAttr(VReg, Flags);
3902 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3903
3904 if (ObjectVT == MVT::f32) {
3905 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3906 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3907 DAG.getConstant(32, dl, MVT::i32));
3908 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3909 }
3910
3911 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3912 } else {
3913 if (CallConv == CallingConv::Fast)
3914 ComputeArgOffset();
3915
3916 needsLoad = true;
3917 }
3918
3919 // When passing an array of floats, the array occupies consecutive
3920 // space in the argument area; only round up to the next doubleword
3921 // at the end of the array. Otherwise, each float takes 8 bytes.
3922 if (CallConv != CallingConv::Fast || needsLoad) {
3923 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3924 ArgOffset += ArgSize;
3925 if (Flags.isInConsecutiveRegsLast())
3926 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3927 }
3928 break;
3929 case MVT::v4f32:
3930 case MVT::v4i32:
3931 case MVT::v8i16:
3932 case MVT::v16i8:
3933 case MVT::v2f64:
3934 case MVT::v2i64:
3935 case MVT::v1i128:
3936 case MVT::f128:
3937 if (!Subtarget.hasQPX()) {
3938 // These can be scalar arguments or elements of a vector array type
3939 // passed directly. The latter are used to implement ELFv2 homogenous
3940 // vector aggregates.
3941 if (VR_idx != Num_VR_Regs) {
3942 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3943 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3944 ++VR_idx;
3945 } else {
3946 if (CallConv == CallingConv::Fast)
3947 ComputeArgOffset();
3948 needsLoad = true;
3949 }
3950 if (CallConv != CallingConv::Fast || needsLoad)
3951 ArgOffset += 16;
3952 break;
3953 } // not QPX
3954
3955 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3956 "Invalid QPX parameter type");
3957 LLVM_FALLTHROUGH;
3958
3959 case MVT::v4f64:
3960 case MVT::v4i1:
3961 // QPX vectors are treated like their scalar floating-point subregisters
3962 // (except that they're larger).
3963 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3964 if (QFPR_idx != Num_QFPR_Regs) {
3965 const TargetRegisterClass *RC;
3966 switch (ObjectVT.getSimpleVT().SimpleTy) {
3967 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3968 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3969 default: RC = &PPC::QBRCRegClass; break;
3970 }
3971
3972 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3973 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3974 ++QFPR_idx;
3975 } else {
3976 if (CallConv == CallingConv::Fast)
3977 ComputeArgOffset();
3978 needsLoad = true;
3979 }
3980 if (CallConv != CallingConv::Fast || needsLoad)
3981 ArgOffset += Sz;
3982 break;
3983 }
3984
3985 // We need to load the argument to a virtual register if we determined
3986 // above that we ran out of physical registers of the appropriate type.
3987 if (needsLoad) {
3988 if (ObjSize < ArgSize && !isLittleEndian)
3989 CurArgOffset += ArgSize - ObjSize;
3990 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3991 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3992 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3993 }
3994
3995 InVals.push_back(ArgVal);
3996 }
3997
3998 // Area that is at least reserved in the caller of this function.
3999 unsigned MinReservedArea;
4000 if (HasParameterArea)
4001 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4002 else
4003 MinReservedArea = LinkageSize;
4004
4005 // Set the size that is at least reserved in caller of this function. Tail
4006 // call optimized functions' reserved stack space needs to be aligned so that
4007 // taking the difference between two stack areas will result in an aligned
4008 // stack.
4009 MinReservedArea =
4010 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4011 FuncInfo->setMinReservedArea(MinReservedArea);
4012
4013 // If the function takes variable number of arguments, make a frame index for
4014 // the start of the first vararg value... for expansion of llvm.va_start.
4015 if (isVarArg) {
4016 int Depth = ArgOffset;
4017
4018 FuncInfo->setVarArgsFrameIndex(
4019 MFI.CreateFixedObject(PtrByteSize, Depth, true));
4020 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4021
4022 // If this function is vararg, store any remaining integer argument regs
4023 // to their spots on the stack so that they may be loaded by dereferencing
4024 // the result of va_next.
4025 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4026 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4027 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4028 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4029 SDValue Store =
4030 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4031 MemOps.push_back(Store);
4032 // Increment the address by four for the next argument to store
4033 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4034 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4035 }
4036 }
4037
4038 if (!MemOps.empty())
4039 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4040
4041 return Chain;
4042}
4043
4044SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4045 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4046 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4047 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4048 // TODO: add description of PPC stack frame format, or at least some docs.
4049 //
4050 MachineFunction &MF = DAG.getMachineFunction();
4051 MachineFrameInfo &MFI = MF.getFrameInfo();
4052 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4053
4054 EVT PtrVT = getPointerTy(MF.getDataLayout());
4055 bool isPPC64 = PtrVT == MVT::i64;
4056 // Potential tail calls could cause overwriting of argument stack slots.
4057 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4058 (CallConv == CallingConv::Fast));
4059 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4060 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4061 unsigned ArgOffset = LinkageSize;
4062 // Area that is at least reserved in caller of this function.
4063 unsigned MinReservedArea = ArgOffset;
4064
4065 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4066 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4067 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4068 };
4069 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4070 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4071 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4072 };
4073 static const MCPhysReg VR[] = {
4074 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4075 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4076 };
4077
4078 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4079 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4080 const unsigned Num_VR_Regs = array_lengthof( VR);
4081
4082 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4083
4084 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4085
4086 // In 32-bit non-varargs functions, the stack space for vectors is after the
4087 // stack space for non-vectors. We do not use this space unless we have
4088 // too many vectors to fit in registers, something that only occurs in
4089 // constructed examples:), but we have to walk the arglist to figure
4090 // that out...for the pathological case, compute VecArgOffset as the
4091 // start of the vector parameter area. Computing VecArgOffset is the
4092 // entire point of the following loop.
4093 unsigned VecArgOffset = ArgOffset;
4094 if (!isVarArg && !isPPC64) {
4095 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4096 ++ArgNo) {
4097 EVT ObjectVT = Ins[ArgNo].VT;
4098 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4099
4100 if (Flags.isByVal()) {
4101 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4102 unsigned ObjSize = Flags.getByValSize();
4103 unsigned ArgSize =
4104 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4105 VecArgOffset += ArgSize;
4106 continue;
4107 }
4108
4109 switch(ObjectVT.getSimpleVT().SimpleTy) {
4110 default: llvm_unreachable("Unhandled argument type!");
4111 case MVT::i1:
4112 case MVT::i32:
4113 case MVT::f32:
4114 VecArgOffset += 4;
4115 break;
4116 case MVT::i64: // PPC64
4117 case MVT::f64:
4118 // FIXME: We are guaranteed to be !isPPC64 at this point.
4119 // Does MVT::i64 apply?
4120 VecArgOffset += 8;
4121 break;
4122 case MVT::v4f32:
4123 case MVT::v4i32:
4124 case MVT::v8i16:
4125 case MVT::v16i8:
4126 // Nothing to do, we're only looking at Nonvector args here.
4127 break;
4128 }
4129 }
4130 }
4131 // We've found where the vector parameter area in memory is. Skip the
4132 // first 12 parameters; these don't use that memory.
4133 VecArgOffset = ((VecArgOffset+15)/16)*16;
4134 VecArgOffset += 12*16;
4135
4136 // Add DAG nodes to load the arguments or copy them out of registers. On
4137 // entry to a function on PPC, the arguments start after the linkage area,
4138 // although the first ones are often in registers.
4139
4140 SmallVector<SDValue, 8> MemOps;
4141 unsigned nAltivecParamsAtEnd = 0;
4142 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4143 unsigned CurArgIdx = 0;
4144 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4145 SDValue ArgVal;
4146 bool needsLoad = false;
4147 EVT ObjectVT = Ins[ArgNo].VT;
4148 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4149 unsigned ArgSize = ObjSize;
4150 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4151 if (Ins[ArgNo].isOrigArg()) {
4152 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4153 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4154 }
4155 unsigned CurArgOffset = ArgOffset;
4156
4157 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4158 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4159 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4160 if (isVarArg || isPPC64) {
4161 MinReservedArea = ((MinReservedArea+15)/16)*16;
4162 MinReservedArea += CalculateStackSlotSize(ObjectVT,
4163 Flags,
4164 PtrByteSize);
4165 } else nAltivecParamsAtEnd++;
4166 } else
4167 // Calculate min reserved area.
4168 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4169 Flags,
4170 PtrByteSize);
4171
4172 // FIXME the codegen can be much improved in some cases.
4173 // We do not have to keep everything in memory.
4174 if (Flags.isByVal()) {
4175 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4176
4177 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4178 ObjSize = Flags.getByValSize();
4179 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4180 // Objects of size 1 and 2 are right justified, everything else is
4181 // left justified. This means the memory address is adjusted forwards.
4182 if (ObjSize==1 || ObjSize==2) {
4183 CurArgOffset = CurArgOffset + (4 - ObjSize);
4184 }
4185 // The value of the object is its address.
4186 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4187 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4188 InVals.push_back(FIN);
4189 if (ObjSize==1 || ObjSize==2) {
4190 if (GPR_idx != Num_GPR_Regs) {
4191 unsigned VReg;
4192 if (isPPC64)
4193 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4194 else
4195 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4196 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4197 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4198 SDValue Store =
4199 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4200 MachinePointerInfo(&*FuncArg), ObjType);
4201 MemOps.push_back(Store);
4202 ++GPR_idx;
4203 }
4204
4205 ArgOffset += PtrByteSize;
4206
4207 continue;
4208 }
4209 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4210 // Store whatever pieces of the object are in registers
4211 // to memory. ArgOffset will be the address of the beginning
4212 // of the object.
4213 if (GPR_idx != Num_GPR_Regs) {
4214 unsigned VReg;
4215 if (isPPC64)
4216 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4217 else
4218 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4219 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4220 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4221 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4222 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4223 MachinePointerInfo(&*FuncArg, j));
4224 MemOps.push_back(Store);
4225 ++GPR_idx;
4226 ArgOffset += PtrByteSize;
4227 } else {
4228 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4229 break;
4230 }
4231 }
4232 continue;
4233 }
4234
4235 switch (ObjectVT.getSimpleVT().SimpleTy) {
4236 default: llvm_unreachable("Unhandled argument type!");
4237 case MVT::i1:
4238 case MVT::i32:
4239 if (!isPPC64) {
4240 if (GPR_idx != Num_GPR_Regs) {
4241 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4242 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4243
4244 if (ObjectVT == MVT::i1)
4245 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4246
4247 ++GPR_idx;
4248 } else {
4249 needsLoad = true;
4250 ArgSize = PtrByteSize;
4251 }
4252 // All int arguments reserve stack space in the Darwin ABI.
4253 ArgOffset += PtrByteSize;
4254 break;
4255 }
4256 LLVM_FALLTHROUGH;
4257 case MVT::i64: // PPC64
4258 if (GPR_idx != Num_GPR_Regs) {
4259 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4260 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4261
4262 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4263 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4264 // value to MVT::i64 and then truncate to the correct register size.
4265 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4266
4267 ++GPR_idx;
4268 } else {
4269 needsLoad = true;
4270 ArgSize = PtrByteSize;
4271 }
4272 // All int arguments reserve stack space in the Darwin ABI.
4273 ArgOffset += 8;
4274 break;
4275
4276 case MVT::f32:
4277 case MVT::f64:
4278 // Every 4 bytes of argument space consumes one of the GPRs available for
4279 // argument passing.
4280 if (GPR_idx != Num_GPR_Regs) {
4281 ++GPR_idx;
4282 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4283 ++GPR_idx;
4284 }
4285 if (FPR_idx != Num_FPR_Regs) {
4286 unsigned VReg;
4287
4288 if (ObjectVT == MVT::f32)
4289 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4290 else
4291 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4292
4293 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4294 ++FPR_idx;
4295 } else {
4296 needsLoad = true;
4297 }
4298
4299 // All FP arguments reserve stack space in the Darwin ABI.
4300 ArgOffset += isPPC64 ? 8 : ObjSize;
4301 break;
4302 case MVT::v4f32:
4303 case MVT::v4i32:
4304 case MVT::v8i16:
4305 case MVT::v16i8:
4306 // Note that vector arguments in registers don't reserve stack space,
4307 // except in varargs functions.
4308 if (VR_idx != Num_VR_Regs) {
4309 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4310 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4311 if (isVarArg) {
4312 while ((ArgOffset % 16) != 0) {
4313 ArgOffset += PtrByteSize;
4314 if (GPR_idx != Num_GPR_Regs)
4315 GPR_idx++;
4316 }
4317 ArgOffset += 16;
4318 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4319 }
4320 ++VR_idx;
4321 } else {
4322 if (!isVarArg && !isPPC64) {
4323 // Vectors go after all the nonvectors.
4324 CurArgOffset = VecArgOffset;
4325 VecArgOffset += 16;
4326 } else {
4327 // Vectors are aligned.
4328 ArgOffset = ((ArgOffset+15)/16)*16;
4329 CurArgOffset = ArgOffset;
4330 ArgOffset += 16;
4331 }
4332 needsLoad = true;
4333 }
4334 break;
4335 }
4336
4337 // We need to load the argument to a virtual register if we determined above
4338 // that we ran out of physical registers of the appropriate type.
4339 if (needsLoad) {
4340 int FI = MFI.CreateFixedObject(ObjSize,
4341 CurArgOffset + (ArgSize - ObjSize),
4342 isImmutable);
4343 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4344 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4345 }
4346
4347 InVals.push_back(ArgVal);
4348 }
4349
4350 // Allow for Altivec parameters at the end, if needed.
4351 if (nAltivecParamsAtEnd) {
4352 MinReservedArea = ((MinReservedArea+15)/16)*16;
4353 MinReservedArea += 16*nAltivecParamsAtEnd;
4354 }
4355
4356 // Area that is at least reserved in the caller of this function.
4357 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4358
4359 // Set the size that is at least reserved in caller of this function. Tail
4360 // call optimized functions' reserved stack space needs to be aligned so that
4361 // taking the difference between two stack areas will result in an aligned
4362 // stack.
4363 MinReservedArea =
4364 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4365 FuncInfo->setMinReservedArea(MinReservedArea);
4366
4367 // If the function takes variable number of arguments, make a frame index for
4368 // the start of the first vararg value... for expansion of llvm.va_start.
4369 if (isVarArg) {
4370 int Depth = ArgOffset;
4371
4372 FuncInfo->setVarArgsFrameIndex(
4373 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4374 Depth, true));
4375 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4376
4377 // If this function is vararg, store any remaining integer argument regs
4378 // to their spots on the stack so that they may be loaded by dereferencing
4379 // the result of va_next.
4380 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4381 unsigned VReg;
4382
4383 if (isPPC64)
4384 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4385 else
4386 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4387
4388 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4389 SDValue Store =
4390 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4391 MemOps.push_back(Store);
4392 // Increment the address by four for the next argument to store
4393 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4394 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4395 }
4396 }
4397
4398 if (!MemOps.empty())
4399 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4400
4401 return Chain;
4402}
4403
4404/// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4405/// adjusted to accommodate the arguments for the tailcall.
4406static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4407 unsigned ParamSize) {
4408
4409 if (!isTailCall) return 0;
4410
4411 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4412 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4413 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4414 // Remember only if the new adjustment is bigger.
4415 if (SPDiff < FI->getTailCallSPDelta())
4416 FI->setTailCallSPDelta(SPDiff);
4417
4418 return SPDiff;
4419}
4420
4421static bool isFunctionGlobalAddress(SDValue Callee);
4422
4423static bool
4424callsShareTOCBase(const Function *Caller, SDValue Callee,
4425 const TargetMachine &TM) {
4426 // Need a GlobalValue to determine if a Caller and Callee share the same
4427 // TOCBase.
4428 const GlobalValue *GV = nullptr;
4429
4430 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4431 GV = G->getGlobal();
4432 } else if (MCSymbolSDNode *M = dyn_cast<MCSymbolSDNode>(Callee)) {
4433 // On AIX only, we replace GlobalAddressSDNode with MCSymbolSDNode for
4434 // the callee of a direct function call. The MCSymbolSDNode contains the
4435 // MCSymbol for the funtion entry point.
4436 const auto *S = cast<MCSymbolXCOFF>(M->getMCSymbol());
4437 GV = S->getGlobalValue();
4438 }
4439
4440 // If we failed to get a GlobalValue, then pessimistically assume they do not
4441 // share a TOCBase.
4442 if (!GV)
4443 return false;
4444
4445 // The medium and large code models are expected to provide a sufficiently
4446 // large TOC to provide all data addressing needs of a module with a
4447 // single TOC. Since each module will be addressed with a single TOC then we
4448 // only need to check that caller and callee don't cross dso boundaries.
4449 if (CodeModel::Medium == TM.getCodeModel() ||
4450 CodeModel::Large == TM.getCodeModel())
4451 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4452
4453 // Otherwise we need to ensure callee and caller are in the same section,
4454 // since the linker may allocate multiple TOCs, and we don't know which
4455 // sections will belong to the same TOC base.
4456
4457 if (!GV->isStrongDefinitionForLinker())
4458 return false;
4459
4460 // Any explicitly-specified sections and section prefixes must also match.
4461 // Also, if we're using -ffunction-sections, then each function is always in
4462 // a different section (the same is true for COMDAT functions).
4463 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4464 GV->getSection() != Caller->getSection())
4465 return false;
4466 if (const auto *F = dyn_cast<Function>(GV)) {
4467 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4468 return false;
4469 }
4470
4471 // If the callee might be interposed, then we can't assume the ultimate call
4472 // target will be in the same section. Even in cases where we can assume that
4473 // interposition won't happen, in any case where the linker might insert a
4474 // stub to allow for interposition, we must generate code as though
4475 // interposition might occur. To understand why this matters, consider a
4476 // situation where: a -> b -> c where the arrows indicate calls. b and c are
4477 // in the same section, but a is in a different module (i.e. has a different
4478 // TOC base pointer). If the linker allows for interposition between b and c,
4479 // then it will generate a stub for the call edge between b and c which will
4480 // save the TOC pointer into the designated stack slot allocated by b. If we
4481 // return true here, and therefore allow a tail call between b and c, that
4482 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4483 // pointer into the stack slot allocated by a (where the a -> b stub saved
4484 // a's TOC base pointer). If we're not considering a tail call, but rather,
4485 // whether a nop is needed after the call instruction in b, because the linker
4486 // will insert a stub, it might complain about a missing nop if we omit it
4487 // (although many don't complain in this case).
4488 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4489 return false;
4490
4491 return true;
4492}
4493
4494static bool
4495needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4496 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4497 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4498
4499 const unsigned PtrByteSize = 8;
4500 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4501
4502 static const MCPhysReg GPR[] = {
4503 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4504 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4505 };
4506 static const MCPhysReg VR[] = {
4507 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4508 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4509 };
4510
4511 const unsigned NumGPRs = array_lengthof(GPR);
4512 const unsigned NumFPRs = 13;
4513 const unsigned NumVRs = array_lengthof(VR);
4514 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4515
4516 unsigned NumBytes = LinkageSize;
4517 unsigned AvailableFPRs = NumFPRs;
4518 unsigned AvailableVRs = NumVRs;
4519
4520 for (const ISD::OutputArg& Param : Outs) {
4521 if (Param.Flags.isNest()) continue;
4522
4523 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4524 PtrByteSize, LinkageSize, ParamAreaSize,
4525 NumBytes, AvailableFPRs, AvailableVRs,
4526 Subtarget.hasQPX()))
4527 return true;
4528 }
4529 return false;
4530}
4531
4532static bool
4533hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4534 if (CS.arg_size() != CallerFn->arg_size())
4535 return false;
4536
4537 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4538 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4539 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4540
4541 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4542 const Value* CalleeArg = *CalleeArgIter;
4543 const Value* CallerArg = &(*CallerArgIter);
4544 if (CalleeArg == CallerArg)
4545 continue;
4546
4547 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4548 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4549 // }
4550 // 1st argument of callee is undef and has the same type as caller.
4551 if (CalleeArg->getType() == CallerArg->getType() &&
4552 isa<UndefValue>(CalleeArg))
4553 continue;
4554
4555 return false;
4556 }
4557
4558 return true;
4559}
4560
4561// Returns true if TCO is possible between the callers and callees
4562// calling conventions.
4563static bool
4564areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4565 CallingConv::ID CalleeCC) {
4566 // Tail calls are possible with fastcc and ccc.
4567 auto isTailCallableCC = [] (CallingConv::ID CC){
4568 return CC == CallingConv::C || CC == CallingConv::Fast;
4569 };
4570 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4571 return false;
4572
4573 // We can safely tail call both fastcc and ccc callees from a c calling
4574 // convention caller. If the caller is fastcc, we may have less stack space
4575 // than a non-fastcc caller with the same signature so disable tail-calls in
4576 // that case.
4577 return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4578}
4579
4580bool
4581PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4582 SDValue Callee,
4583 CallingConv::ID CalleeCC,
4584 ImmutableCallSite CS,
4585 bool isVarArg,
4586 const SmallVectorImpl<ISD::OutputArg> &Outs,
4587 const SmallVectorImpl<ISD::InputArg> &Ins,
4588 SelectionDAG& DAG) const {
4589 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4590
4591 if (DisableSCO && !TailCallOpt) return false;
4592
4593 // Variadic argument functions are not supported.
4594 if (isVarArg) return false;
4595
4596 auto &Caller = DAG.getMachineFunction().getFunction();
4597 // Check that the calling conventions are compatible for tco.
4598 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4599 return false;
4600
4601 // Caller contains any byval parameter is not supported.
4602 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4603 return false;
4604
4605 // Callee contains any byval parameter is not supported, too.
4606 // Note: This is a quick work around, because in some cases, e.g.
4607 // caller's stack size > callee's stack size, we are still able to apply
4608 // sibling call optimization. For example, gcc is able to do SCO for caller1
4609 // in the following example, but not for caller2.
4610 // struct test {
4611 // long int a;
4612 // char ary[56];
4613 // } gTest;
4614 // __attribute__((noinline)) int callee(struct test v, struct test *b) {
4615 // b->a = v.a;
4616 // return 0;
4617 // }
4618 // void caller1(struct test a, struct test c, struct test *b) {
4619 // callee(gTest, b); }
4620 // void caller2(struct test *b) { callee(gTest, b); }
4621 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4622 return false;
4623
4624 // If callee and caller use different calling conventions, we cannot pass
4625 // parameters on stack since offsets for the parameter area may be different.
4626 if (Caller.getCallingConv() != CalleeCC &&
4627 needStackSlotPassParameters(Subtarget, Outs))
4628 return false;
4629
4630 // No TCO/SCO on indirect call because Caller have to restore its TOC
4631 if (!isFunctionGlobalAddress(Callee) &&
4632 !isa<ExternalSymbolSDNode>(Callee))
4633 return false;
4634
4635 // If the caller and callee potentially have different TOC bases then we
4636 // cannot tail call since we need to restore the TOC pointer after the call.
4637 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4638 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4639 return false;
4640
4641 // TCO allows altering callee ABI, so we don't have to check further.
4642 if (CalleeCC == CallingConv::Fast && TailCallOpt)
4643 return true;
4644
4645 if (DisableSCO) return false;
4646
4647 // If callee use the same argument list that caller is using, then we can
4648 // apply SCO on this case. If it is not, then we need to check if callee needs
4649 // stack for passing arguments.
4650 if (!hasSameArgumentList(&Caller, CS) &&
4651 needStackSlotPassParameters(Subtarget, Outs)) {
4652 return false;
4653 }
4654
4655 return true;
4656}
4657
4658/// IsEligibleForTailCallOptimization - Check whether the call is eligible
4659/// for tail call optimization. Targets which want to do tail call
4660/// optimization should implement this function.
4661bool
4662PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4663 CallingConv::ID CalleeCC,
4664 bool isVarArg,
4665 const SmallVectorImpl<ISD::InputArg> &Ins,
4666 SelectionDAG& DAG) const {
4667 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4668 return false;
4669
4670 // Variable argument functions are not supported.
4671 if (isVarArg)
4672 return false;
4673
4674 MachineFunction &MF = DAG.getMachineFunction();
4675 CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4676 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4677 // Functions containing by val parameters are not supported.
4678 for (unsigned i = 0; i != Ins.size(); i++) {
4679 ISD::ArgFlagsTy Flags = Ins[i].Flags;
4680 if (Flags.isByVal()) return false;
4681 }
4682
4683 // Non-PIC/GOT tail calls are supported.
4684 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4685 return true;
4686
4687 // At the moment we can only do local tail calls (in same module, hidden
4688 // or protected) if we are generating PIC.
4689 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4690 return G->getGlobal()->hasHiddenVisibility()
4691 || G->getGlobal()->hasProtectedVisibility();
4692 }
4693
4694 return false;
4695}
4696
4697/// isCallCompatibleAddress - Return the immediate to use if the specified
4698/// 32-bit value is representable in the immediate field of a BxA instruction.
4699static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4700 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4701 if (!C) return nullptr;
4702
4703 int Addr = C->getZExtValue();
4704 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
4705 SignExtend32<26>(Addr) != Addr)
4706 return nullptr; // Top 6 bits have to be sext of immediate.
4707
4708 return DAG
4709 .getConstant(
4710 (int)C->getZExtValue() >> 2, SDLoc(Op),
4711 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4712 .getNode();
4713}
4714
4715namespace {
4716
4717struct TailCallArgumentInfo {
4718 SDValue Arg;
4719 SDValue FrameIdxOp;
4720 int FrameIdx = 0;
4721
4722 TailCallArgumentInfo() = default;
4723};
4724
4725} // end anonymous namespace
4726
4727/// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4728static void StoreTailCallArgumentsToStackSlot(
4729 SelectionDAG &DAG, SDValue Chain,
4730 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4731 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4732 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4733 SDValue Arg = TailCallArgs[i].Arg;
4734 SDValue FIN = TailCallArgs[i].FrameIdxOp;
4735 int FI = TailCallArgs[i].FrameIdx;
4736 // Store relative to framepointer.
4737 MemOpChains.push_back(DAG.getStore(
4738 Chain, dl, Arg, FIN,
4739 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4740 }
4741}
4742
4743/// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4744/// the appropriate stack slot for the tail call optimized function call.
4745static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4746 SDValue OldRetAddr, SDValue OldFP,
4747 int SPDiff, const SDLoc &dl) {
4748 if (SPDiff) {
4749 // Calculate the new stack slot for the return address.
4750 MachineFunction &MF = DAG.getMachineFunction();
4751 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4752 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4753 bool isPPC64 = Subtarget.isPPC64();
4754 int SlotSize = isPPC64 ? 8 : 4;
4755 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4756 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4757 NewRetAddrLoc, true);
4758 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4759 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4760 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4761 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4762
4763 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4764 // slot as the FP is never overwritten.
4765 if (Subtarget.isDarwinABI()) {
4766 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4767 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4768 true);
4769 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4770 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4771 MachinePointerInfo::getFixedStack(
4772 DAG.getMachineFunction(), NewFPIdx));
4773 }
4774 }
4775 return Chain;
4776}
4777
4778/// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4779/// the position of the argument.
4780static void
4781CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4782 SDValue Arg, int SPDiff, unsigned ArgOffset,
4783 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4784 int Offset = ArgOffset + SPDiff;
4785 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4786 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4787 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4788 SDValue FIN = DAG.getFrameIndex(FI, VT);
4789 TailCallArgumentInfo Info;
4790 Info.Arg = Arg;
4791 Info.FrameIdxOp = FIN;
4792 Info.FrameIdx = FI;
4793 TailCallArguments.push_back(Info);
4794}
4795
4796/// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4797/// stack slot. Returns the chain as result and the loaded frame pointers in
4798/// LROpOut/FPOpout. Used when tail calling.
4799SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4800 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4801 SDValue &FPOpOut, const SDLoc &dl) const {
4802 if (SPDiff) {
4803 // Load the LR and FP stack slot for later adjusting.
4804 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4805 LROpOut = getReturnAddrFrameIndex(DAG);
4806 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4807 Chain = SDValue(LROpOut.getNode(), 1);
4808
4809 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4810 // slot as the FP is never overwritten.
4811 if (Subtarget.isDarwinABI()) {
4812 FPOpOut = getFramePointerFrameIndex(DAG);
4813 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4814 Chain = SDValue(FPOpOut.getNode(), 1);
4815 }
4816 }
4817 return Chain;
4818}
4819
4820/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4821/// by "Src" to address "Dst" of size "Size". Alignment information is
4822/// specified by the specific parameter attribute. The copy will be passed as
4823/// a byval function parameter.
4824/// Sometimes what we are copying is the end of a larger object, the part that
4825/// does not fit in registers.
4826static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4827 SDValue Chain, ISD::ArgFlagsTy Flags,
4828 SelectionDAG &DAG, const SDLoc &dl) {
4829 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4830 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4831 false, false, false, false, MachinePointerInfo(),
4832 MachinePointerInfo());
4833}
4834
4835/// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4836/// tail calls.
4837static void LowerMemOpCallTo(
4838 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4839 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4840 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4841 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4842 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4843 if (!isTailCall) {
4844 if (isVector) {
4845 SDValue StackPtr;
4846 if (isPPC64)
4847 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4848 else
4849 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4850 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4851 DAG.getConstant(ArgOffset, dl, PtrVT));
4852 }
4853 MemOpChains.push_back(
4854 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4855 // Calculate and remember argument location.
4856 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4857 TailCallArguments);
4858}
4859
4860static void
4861PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4862 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4863 SDValue FPOp,
4864 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4865 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4866 // might overwrite each other in case of tail call optimization.
4867 SmallVector<SDValue, 8> MemOpChains2;
4868 // Do not flag preceding copytoreg stuff together with the following stuff.
4869 InFlag = SDValue();
4870 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4871 MemOpChains2, dl);
4872 if (!MemOpChains2.empty())
4873 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4874
4875 // Store the return address to the appropriate stack slot.
4876 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4877
4878 // Emit callseq_end just before tailcall node.
4879 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4880 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4881 InFlag = Chain.getValue(1);
4882}
4883
4884// Is this global address that of a function that can be called by name? (as
4885// opposed to something that must hold a descriptor for an indirect call).
4886static bool isFunctionGlobalAddress(SDValue Callee) {
4887 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4888 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4889 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4890 return false;
4891
4892 return G->getGlobal()->getValueType()->isFunctionTy();
4893 }
4894
4895 return false;
4896}
4897
4898static unsigned
4899PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4900 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4901 bool isPatchPoint, bool hasNest,
4902 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4903 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4904 ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4905 bool isPPC64 = Subtarget.isPPC64();
4906 bool isSVR4ABI = Subtarget.isSVR4ABI();
4907 bool isELFv2ABI = Subtarget.isELFv2ABI();
4908 bool isAIXABI = Subtarget.isAIXABI();
4909
4910 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4911 NodeTys.push_back(MVT::Other); // Returns a chain
4912 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
4913
4914 unsigned CallOpc = PPCISD::CALL;
4915
4916 bool needIndirectCall = true;
4917 if (!isSVR4ABI || !isPPC64)
4918 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4919 // If this is an absolute destination address, use the munged value.
4920 Callee = SDValue(Dest, 0);
4921 needIndirectCall = false;
4922 }
4923
4924 // PC-relative references to external symbols should go through $stub, unless
4925 // we're building with the leopard linker or later, which automatically
4926 // synthesizes these stubs.
4927 const TargetMachine &TM = DAG.getTarget();
4928 MachineFunction &MF = DAG.getMachineFunction();
4929 const Module *Mod = MF.getFunction().getParent();
4930 const GlobalValue *GV = nullptr;
4931 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4932 GV = G->getGlobal();
4933 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4934 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4935
4936 if (isFunctionGlobalAddress(Callee)) {
4937 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4938
4939 if (TM.getTargetTriple().isOSAIX()) {
4940 // Direct function calls reference the symbol for the function's entry
4941 // point, which is named by inserting a "." before the function's
4942 // C-linkage name.
4943 auto &Context = MF.getMMI().getContext();
4944 MCSymbol *S = Context.getOrCreateSymbol(Twine(".") +
4945 Twine(G->getGlobal()->getName()));
4946 cast<MCSymbolXCOFF>(S)->setGlobalValue(GV);
4947 Callee = DAG.getMCSymbol(S, PtrVT);
4948 } else {
4949 // A call to a TLS address is actually an indirect call to a
4950 // thread-specific pointer.
4951 unsigned OpFlags = 0;
4952 if (UsePlt)
4953 OpFlags = PPCII::MO_PLT;
4954
4955 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4956 // every direct call is) turn it into a TargetGlobalAddress /
4957 // TargetExternalSymbol node so that legalize doesn't hack it.
4958 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4959 Callee.getValueType(), 0, OpFlags);
4960 }
4961 needIndirectCall = false;
4962 }
4963
4964 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4965 unsigned char OpFlags = 0;
4966
4967 if (UsePlt)
4968 OpFlags = PPCII::MO_PLT;
4969
4970 Callee = DAG.getTargetExternalFunctionSymbol(S->getSymbol(), OpFlags);
4971 needIndirectCall = false;
4972 }
4973
4974 if (isPatchPoint) {
4975 // We'll form an invalid direct call when lowering a patchpoint; the full
4976 // sequence for an indirect call is complicated, and many of the
4977 // instructions introduced might have side effects (and, thus, can't be
4978 // removed later). The call itself will be removed as soon as the
4979 // argument/return lowering is complete, so the fact that it has the wrong
4980 // kind of operands should not really matter.
4981 needIndirectCall = false;
4982 }
4983
4984 if (needIndirectCall) {
4985 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
4986 // to do the call, we can't use PPCISD::CALL.
4987 SDValue MTCTROps[] = {Chain, Callee, InFlag};
4988
4989 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4990 // Function pointers in the 64-bit SVR4 ABI do not point to the function
4991 // entry point, but to the function descriptor (the function entry point
4992 // address is part of the function descriptor though).
4993 // The function descriptor is a three doubleword structure with the
4994 // following fields: function entry point, TOC base address and
4995 // environment pointer.
4996 // Thus for a call through a function pointer, the following actions need
4997 // to be performed:
4998 // 1. Save the TOC of the caller in the TOC save area of its stack
4999 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5000 // 2. Load the address of the function entry point from the function
5001 // descriptor.
5002 // 3. Load the TOC of the callee from the function descriptor into r2.
5003 // 4. Load the environment pointer from the function descriptor into
5004 // r11.
5005 // 5. Branch to the function entry point address.
5006 // 6. On return of the callee, the TOC of the caller needs to be
5007 // restored (this is done in FinishCall()).
5008 //
5009 // The loads are scheduled at the beginning of the call sequence, and the
5010 // register copies are flagged together to ensure that no other
5011 // operations can be scheduled in between. E.g. without flagging the
5012 // copies together, a TOC access in the caller could be scheduled between
5013 // the assignment of the callee TOC and the branch to the callee, which
5014 // results in the TOC access going through the TOC of the callee instead
5015 // of going through the TOC of the caller, which leads to incorrect code.
5016
5017 // Load the address of the function entry point from the function
5018 // descriptor.
5019 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
5020 if (LDChain.getValueType() == MVT::Glue)
5021 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
5022
5023 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5024 ? (MachineMemOperand::MODereferenceable |
5025 MachineMemOperand::MOInvariant)
5026 : MachineMemOperand::MONone;
5027
5028 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5029 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
5030 /* Alignment = */ 8, MMOFlags);
5031
5032 // Load environment pointer into r11.
5033 SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
5034 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
5035 SDValue LoadEnvPtr =
5036 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
5037 /* Alignment = */ 8, MMOFlags);
5038
5039 SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
5040 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
5041 SDValue TOCPtr =
5042 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
5043 /* Alignment = */ 8, MMOFlags);
5044
5045 setUsesTOCBasePtr(DAG);
5046 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
5047 InFlag);
5048 Chain = TOCVal.getValue(0);
5049 InFlag = TOCVal.getValue(1);
5050
5051 // If the function call has an explicit 'nest' parameter, it takes the
5052 // place of the environment pointer.
5053 if (!hasNest) {
5054 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
5055 InFlag);
5056
5057 Chain = EnvVal.getValue(0);
5058 InFlag = EnvVal.getValue(1);
5059 }
5060
5061 MTCTROps[0] = Chain;
5062 MTCTROps[1] = LoadFuncPtr;
5063 MTCTROps[2] = InFlag;
5064 }
5065
5066 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
5067 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
5068 InFlag = Chain.getValue(1);
5069
5070 NodeTys.clear();
5071 NodeTys.push_back(MVT::Other);
5072 NodeTys.push_back(MVT::Glue);
5073 Ops.push_back(Chain);
5074 CallOpc = PPCISD::BCTRL;
5075 Callee.setNode(nullptr);
5076 // Add use of X11 (holding environment pointer)
5077 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
5078 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
5079 // Add CTR register as callee so a bctr can be emitted later.
5080 if (isTailCall)
5081 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
5082 }
5083
5084 // If this is a direct call, pass the chain and the callee.
5085 if (Callee.getNode()) {
5086 Ops.push_back(Chain);
5087 Ops.push_back(Callee);
5088 }
5089 // If this is a tail call add stack pointer delta.
5090 if (isTailCall)
5091 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5092
5093 // Add argument registers to the end of the list so that they are known live
5094 // into the call.
5095 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5096 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5097 RegsToPass[i].second.getValueType()));
5098
5099 // All calls, in the AIX ABI and 64-bit ELF ABIs, need the TOC register
5100 // live into the call.
5101 // We do need to reserve R2/X2 to appease the verifier for the PATCHPOINT.
5102 if ((isSVR4ABI && isPPC64) || isAIXABI) {
5103 setUsesTOCBasePtr(DAG);
5104
5105 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5106 // no way to mark dependencies as implicit here.
5107 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5108 if (!isPatchPoint)
5109 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::X2
5110 : PPC::R2, PtrVT));
5111 }
5112
5113 return CallOpc;
5114}
5115
5116SDValue PPCTargetLowering::LowerCallResult(
5117 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5118 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5119 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5120 SmallVector<CCValAssign, 16> RVLocs;
5121 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5122 *DAG.getContext());
5123
5124 CCRetInfo.AnalyzeCallResult(
5125 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5126 ? RetCC_PPC_Cold
5127 : RetCC_PPC);
5128
5129 // Copy all of the result registers out of their specified physreg.
5130 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5131 CCValAssign &VA = RVLocs[i];
5132 assert(VA.isRegLoc() && "Can only return in registers!");
5133
5134 SDValue Val = DAG.getCopyFromReg(Chain, dl,
5135 VA.getLocReg(), VA.getLocVT(), InFlag);
5136 Chain = Val.getValue(1);
5137 InFlag = Val.getValue(2);
5138
5139 switch (VA.getLocInfo()) {
5140 default: llvm_unreachable("Unknown loc info!");
5141 case CCValAssign::Full: break;
5142 case CCValAssign::AExt:
5143 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5144 break;
5145 case CCValAssign::ZExt:
5146 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5147 DAG.getValueType(VA.getValVT()));
5148 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5149 break;
5150 case CCValAssign::SExt:
5151 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5152 DAG.getValueType(VA.getValVT()));
5153 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5154 break;
5155 }
5156
5157 InVals.push_back(Val);
5158 }
5159
5160 return Chain;
5161}
5162
5163SDValue PPCTargetLowering::FinishCall(
5164 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5165 bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5166 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
5167 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5168 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5169 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5170 std::vector<EVT> NodeTys;
5171 SmallVector<SDValue, 8> Ops;
5172 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
5173 SPDiff, isTailCall, isPatchPoint, hasNest,
5174 RegsToPass, Ops, NodeTys, CS, Subtarget);
5175
5176 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5177 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
5178 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5179
5180 // When performing tail call optimization the callee pops its arguments off
5181 // the stack. Account for this here so these bytes can be pushed back on in
5182 // PPCFrameLowering::eliminateCallFramePseudoInstr.
5183 int BytesCalleePops =
5184 (CallConv == CallingConv::Fast &&
5185 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
5186
5187 // Add a register mask operand representing the call-preserved registers.
5188 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5189 const uint32_t *Mask =
5190 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5191 assert(Mask && "Missing call preserved mask for calling convention");
5192 Ops.push_back(DAG.getRegisterMask(Mask));
5193
5194 if (InFlag.getNode())
5195 Ops.push_back(InFlag);
5196
5197 // Emit tail call.
5198 if (isTailCall) {
5199 assert(((Callee.getOpcode() == ISD::Register &&
5200 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5201 Callee.getOpcode() == ISD::TargetExternalSymbol ||
5202 Callee.getOpcode() == ISD::TargetGlobalAddress ||
5203 isa<ConstantSDNode>(Callee)) &&
5204 "Expecting an global address, external symbol, absolute value or register");
5205
5206 DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5207 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5208 }
5209
5210 // Add a NOP immediately after the branch instruction when using the 64-bit
5211 // SVR4 or the AIX ABI.
5212 // At link time, if caller and callee are in a different module and
5213 // thus have a different TOC, the call will be replaced with a call to a stub
5214 // function which saves the current TOC, loads the TOC of the callee and
5215 // branches to the callee. The NOP will be replaced with a load instruction
5216 // which restores the TOC of the caller from the TOC save slot of the current
5217 // stack frame. If caller and callee belong to the same module (and have the
5218 // same TOC), the NOP will remain unchanged, or become some other NOP.
5219
5220 MachineFunction &MF = DAG.getMachineFunction();
5221 if (!isTailCall && !isPatchPoint &&
5222 ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) ||
5223 Subtarget.isAIXABI())) {
5224 if (CallOpc == PPCISD::BCTRL) {
5225 if (Subtarget.isAIXABI())
5226 report_fatal_error("Indirect call on AIX is not implemented.");
5227
5228 // This is a call through a function pointer.
5229 // Restore the caller TOC from the save area into R2.
5230 // See PrepareCall() for more information about calls through function
5231 // pointers in the 64-bit SVR4 ABI.
5232 // We are using a target-specific load with r2 hard coded, because the
5233 // result of a target-independent load would never go directly into r2,
5234 // since r2 is a reserved register (which prevents the register allocator
5235 // from allocating it), resulting in an additional register being
5236 // allocated and an unnecessary move instruction being generated.
5237 CallOpc = PPCISD::BCTRL_LOAD_TOC;
5238
5239 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5240 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5241 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5242 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5243 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5244
5245 // The address needs to go after the chain input but before the flag (or
5246 // any other variadic arguments).
5247 Ops.insert(std::next(Ops.begin()), AddTOC);
5248 } else if (CallOpc == PPCISD::CALL &&
5249 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5250 // Otherwise insert NOP for non-local calls.
5251 CallOpc = PPCISD::CALL_NOP;
5252 }
5253 }
5254
5255 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5256 InFlag = Chain.getValue(1);
5257
5258 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5259 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5260 InFlag, dl);
5261 if (!Ins.empty())
5262 InFlag = Chain.getValue(1);
5263
5264 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5265 Ins, dl, DAG, InVals);
5266}
5267
5268SDValue
5269PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5270 SmallVectorImpl<SDValue> &InVals) const {
5271 SelectionDAG &DAG = CLI.DAG;
5272 SDLoc &dl = CLI.DL;
5273 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5274 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
5275 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
5276 SDValue Chain = CLI.Chain;
5277 SDValue Callee = CLI.Callee;
5278 bool &isTailCall = CLI.IsTailCall;
5279 CallingConv::ID CallConv = CLI.CallConv;
5280 bool isVarArg = CLI.IsVarArg;
5281 bool isPatchPoint = CLI.IsPatchPoint;
5282 ImmutableCallSite CS = CLI.CS;
5283
5284 if (isTailCall) {
5285 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5286 isTailCall = false;
5287 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5288 isTailCall =
5289 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5290 isVarArg, Outs, Ins, DAG);
5291 else
5292 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5293 Ins, DAG);
5294 if (isTailCall) {
5295 ++NumTailCalls;
5296 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5297 ++NumSiblingCalls;
5298
5299 assert(isa<GlobalAddressSDNode>(Callee) &&
5300 "Callee should be an llvm::Function object.");
5301 LLVM_DEBUG(
5302 const GlobalValue *GV =
5303 cast<GlobalAddressSDNode>(Callee)->getGlobal();
5304 const unsigned Width =
5305 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5306 dbgs() << "TCO caller: "
5307 << left_justify(DAG.getMachineFunction().getName(), Width)
5308 << ", callee linkage: " << GV->getVisibility() << ", "
5309 << GV->getLinkage() << "\n");
5310 }
5311 }
5312
5313 if (!isTailCall && CS && CS.isMustTailCall())
5314 report_fatal_error("failed to perform tail call elimination on a call "
5315 "site marked musttail");
5316
5317 // When long calls (i.e. indirect calls) are always used, calls are always
5318 // made via function pointer. If we have a function name, first translate it
5319 // into a pointer.
5320 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5321 !isTailCall)
5322 Callee = LowerGlobalAddress(Callee, DAG);
5323
5324 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5325 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5326 isTailCall, isPatchPoint, Outs, OutVals, Ins,
5327 dl, DAG, InVals, CS);
5328
5329 if (Subtarget.isSVR4ABI())
5330 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5331 isTailCall, isPatchPoint, Outs, OutVals, Ins,
5332 dl, DAG, InVals, CS);
5333
5334 if (Subtarget.isAIXABI())
5335 return LowerCall_AIX(Chain, Callee, CallConv, isVarArg,
5336 isTailCall, isPatchPoint, Outs, OutVals, Ins,
5337 dl, DAG, InVals, CS);
5338
5339 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5340 isTailCall, isPatchPoint, Outs, OutVals, Ins,
5341 dl, DAG, InVals, CS);
5342}
5343
5344SDValue PPCTargetLowering::LowerCall_32SVR4(
5345 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5346 bool isTailCall, bool isPatchPoint,
5347 const SmallVectorImpl<ISD::OutputArg> &Outs,
5348 const SmallVectorImpl<SDValue> &OutVals,
5349 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5350 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5351 ImmutableCallSite CS) const {
5352 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5353 // of the 32-bit SVR4 ABI stack frame layout.
5354
5355 assert((CallConv == CallingConv::C ||
5356 CallConv == CallingConv::Cold ||
5357 CallConv == CallingConv::Fast) && "Unknown calling convention!");
5358
5359 unsigned PtrByteSize = 4;
5360
5361 MachineFunction &MF = DAG.getMachineFunction();
5362
5363 // Mark this function as potentially containing a function that contains a
5364 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5365 // and restoring the callers stack pointer in this functions epilog. This is
5366 // done because by tail calling the called function might overwrite the value
5367 // in this function's (MF) stack pointer stack slot 0(SP).
5368 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5369 CallConv == CallingConv::Fast)
5370 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5371
5372 // Count how many bytes are to be pushed on the stack, including the linkage
5373 // area, parameter list area and the part of the local variable space which
5374 // contains copies of aggregates which are passed by value.
5375
5376 // Assign locations to all of the outgoing arguments.
5377 SmallVector<CCValAssign, 16> ArgLocs;
5378 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5379
5380 // Reserve space for the linkage area on the stack.
5381 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5382 PtrByteSize);
5383 if (useSoftFloat())
5384 CCInfo.PreAnalyzeCallOperands(Outs);
5385
5386 if (isVarArg) {
5387 // Handle fixed and variable vector arguments differently.
5388 // Fixed vector arguments go into registers as long as registers are
5389 // available. Variable vector arguments always go into memory.
5390 unsigned NumArgs = Outs.size();
5391
5392 for (unsigned i = 0; i != NumArgs; ++i) {
5393 MVT ArgVT = Outs[i].VT;
5394 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5395 bool Result;
5396
5397 if (Outs[i].IsFixed) {
5398 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5399 CCInfo);
5400 } else {
5401 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5402 ArgFlags, CCInfo);
5403 }
5404
5405 if (Result) {
5406#ifndef NDEBUG
5407 errs() << "Call operand #" << i << " has unhandled type "
5408 << EVT(ArgVT).getEVTString() << "\n";
5409#endif
5410 llvm_unreachable(nullptr);
5411 }
5412 }
5413 } else {
5414 // All arguments are treated the same.
5415 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5416 }
5417 CCInfo.clearWasPPCF128();
5418
5419 // Assign locations to all of the outgoing aggregate by value arguments.
5420 SmallVector<CCValAssign, 16> ByValArgLocs;
5421 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5422
5423 // Reserve stack space for the allocations in CCInfo.
5424 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5425
5426 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5427
5428 // Size of the linkage area, parameter list area and the part of the local
5429 // space variable where copies of aggregates which are passed by value are
5430 // stored.
5431 unsigned NumBytes = CCByValInfo.getNextStackOffset();
5432
5433 // Calculate by how many bytes the stack has to be adjusted in case of tail
5434 // call optimization.
5435 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5436
5437 // Adjust the stack pointer for the new arguments...
5438 // These operations are automatically eliminated by the prolog/epilog pass
5439 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5440 SDValue CallSeqStart = Chain;
5441
5442 // Load the return address and frame pointer so it can be moved somewhere else
5443 // later.
5444 SDValue LROp, FPOp;
5445 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5446
5447 // Set up a copy of the stack pointer for use loading and storing any
5448 // arguments that may not fit in the registers available for argument
5449 // passing.
5450 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5451
5452 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5453 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5454 SmallVector<SDValue, 8> MemOpChains;
5455
5456 bool seenFloatArg = false;
5457 // Walk the register/memloc assignments, inserting copies/loads.
5458 for (unsigned i = 0, j = 0, e = ArgLocs.size();
5459 i != e;
5460 ++i) {
5461 CCValAssign &VA = ArgLocs[i];
5462 SDValue Arg = OutVals[i];
5463 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5464
5465 if (Flags.isByVal()) {
5466 // Argument is an aggregate which is passed by value, thus we need to
5467 // create a copy of it in the local variable space of the current stack
5468 // frame (which is the stack frame of the caller) and pass the address of
5469 // this copy to the callee.
5470 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5471 CCValAssign &ByValVA = ByValArgLocs[j++];
5472 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5473
5474 // Memory reserved in the local variable space of the callers stack frame.
5475 unsigned LocMemOffset = ByValVA.getLocMemOffset();
5476
5477 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5478 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5479 StackPtr, PtrOff);
5480
5481 // Create a copy of the argument in the local area of the current
5482 // stack frame.
5483 SDValue MemcpyCall =
5484 CreateCopyOfByValArgument(Arg, PtrOff,
5485 CallSeqStart.getNode()->getOperand(0),
5486 Flags, DAG, dl);
5487
5488 // This must go outside the CALLSEQ_START..END.
5489 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5490 SDLoc(MemcpyCall));
5491 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5492 NewCallSeqStart.getNode());
5493 Chain = CallSeqStart = NewCallSeqStart;
5494
5495 // Pass the address of the aggregate copy on the stack either in a
5496 // physical register or in the parameter list area of the current stack
5497 // frame to the callee.
5498 Arg = PtrOff;
5499 }
5500
5501 // When useCRBits() is true, there can be i1 arguments.
5502 // It is because getRegisterType(MVT::i1) => MVT::i1,
5503 // and for other integer types getRegisterType() => MVT::i32.
5504 // Extend i1 and ensure callee will get i32.
5505 if (Arg.getValueType() == MVT::i1)
5506 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5507 dl, MVT::i32, Arg);
5508
5509 if (VA.isRegLoc()) {
5510 seenFloatArg |= VA.getLocVT().isFloatingPoint();
5511 // Put argument in a physical register.
5512 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5513 } else {
5514 // Put argument in the parameter list area of the current stack frame.
5515 assert(VA.isMemLoc());
5516 unsigned LocMemOffset = VA.getLocMemOffset();
5517
5518 if (!isTailCall) {
5519 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5520 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5521 StackPtr, PtrOff);
5522
5523 MemOpChains.push_back(
5524 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5525 } else {
5526 // Calculate and remember argument location.
5527 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5528 TailCallArguments);
5529 }
5530 }
5531 }
5532
5533 if (!MemOpChains.empty())
5534 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5535
5536 // Build a sequence of copy-to-reg nodes chained together with token chain
5537 // and flag operands which copy the outgoing args into the appropriate regs.
5538 SDValue InFlag;
5539 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5540 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5541 RegsToPass[i].second, InFlag);
5542 InFlag = Chain.getValue(1);
5543 }
5544
5545 // Set CR bit 6 to true if this is a vararg call with floating args passed in
5546 // registers.
5547 if (isVarArg) {
5548 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5549 SDValue Ops[] = { Chain, InFlag };
5550
5551 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5552 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5553
5554 InFlag = Chain.getValue(1);
5555 }
5556
5557 if (isTailCall)
5558 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5559 TailCallArguments);
5560
5561 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5562 /* unused except on PPC64 ELFv1 */ false, DAG,
5563 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5564 NumBytes, Ins, InVals, CS);
5565}
5566
5567// Copy an argument into memory, being careful to do this outside the
5568// call sequence for the call to which the argument belongs.
5569SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5570 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5571 SelectionDAG &DAG, const SDLoc &dl) const {
5572 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5573 CallSeqStart.getNode()->getOperand(0),
5574 Flags, DAG, dl);
5575 // The MEMCPY must go outside the CALLSEQ_START..END.
5576 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5577 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5578 SDLoc(MemcpyCall));
5579 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5580 NewCallSeqStart.getNode());
5581 return NewCallSeqStart;
5582}
5583
5584SDValue PPCTargetLowering::LowerCall_64SVR4(
5585 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5586 bool isTailCall, bool isPatchPoint,
5587 const SmallVectorImpl<ISD::OutputArg> &Outs,
5588 const SmallVectorImpl<SDValue> &OutVals,
5589 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5590 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5591 ImmutableCallSite CS) const {
5592 bool isELFv2ABI = Subtarget.isELFv2ABI();
5593 bool isLittleEndian = Subtarget.isLittleEndian();
5594 unsigned NumOps = Outs.size();
5595 bool hasNest = false;
5596 bool IsSibCall = false;
5597
5598 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5599 unsigned PtrByteSize = 8;
5600
5601 MachineFunction &MF = DAG.getMachineFunction();
5602
5603 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5604 IsSibCall = true;
5605
5606 // Mark this function as potentially containing a function that contains a
5607 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5608 // and restoring the callers stack pointer in this functions epilog. This is
5609 // done because by tail calling the called function might overwrite the value
5610 // in this function's (MF) stack pointer stack slot 0(SP).
5611 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5612 CallConv == CallingConv::Fast)
5613 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5614
5615 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5616 "fastcc not supported on varargs functions");
5617
5618 // Count how many bytes are to be pushed on the stack, including the linkage
5619 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
5620 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5621 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5622 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5623 unsigned NumBytes = LinkageSize;
5624 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5625 unsigned &QFPR_idx = FPR_idx;
5626
5627 static const MCPhysReg GPR[] = {
5628 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5629 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5630 };
5631 static const MCPhysReg VR[] = {
5632 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5633 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5634 };
5635
5636 const unsigned NumGPRs = array_lengthof(GPR);
5637 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5638 const unsigned NumVRs = array_lengthof(VR);
5639 const unsigned NumQFPRs = NumFPRs;
5640
5641 // On ELFv2, we can avoid allocating the parameter area if all the arguments
5642 // can be passed to the callee in registers.
5643 // For the fast calling convention, there is another check below.
5644 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5645 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5646 if (!HasParameterArea) {
5647 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5648 unsigned AvailableFPRs = NumFPRs;
5649 unsigned AvailableVRs = NumVRs;
5650 unsigned NumBytesTmp = NumBytes;
5651 for (unsigned i = 0; i != NumOps; ++i) {
5652 if (Outs[i].Flags.isNest()) continue;
5653 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5654 PtrByteSize, LinkageSize, ParamAreaSize,
5655 NumBytesTmp, AvailableFPRs, AvailableVRs,
5656 Subtarget.hasQPX()))
5657 HasParameterArea = true;
5658 }
5659 }
5660
5661 // When using the fast calling convention, we don't provide backing for
5662 // arguments that will be in registers.
5663 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5664
5665 // Avoid allocating parameter area for fastcc functions if all the arguments
5666 // can be passed in the registers.
5667 if (CallConv == CallingConv::Fast)
5668 HasParameterArea = false;
5669
5670 // Add up all the space actually used.
5671 for (unsigned i = 0; i != NumOps; ++i) {
5672 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5673 EVT ArgVT = Outs[i].VT;
5674 EVT OrigVT = Outs[i].ArgVT;
5675
5676 if (Flags.isNest())
5677 continue;
5678
5679 if (CallConv == CallingConv::Fast) {
5680 if (Flags.isByVal()) {
5681 NumGPRsUsed += (Flags.getByValSize()+7)/8;
5682 if (NumGPRsUsed > NumGPRs)
5683 HasParameterArea = true;
5684 } else {
5685 switch (ArgVT.getSimpleVT().SimpleTy) {
5686 default: llvm_unreachable("Unexpected ValueType for argument!");
5687 case MVT::i1:
5688 case MVT::i32:
5689 case MVT::i64:
5690 if (++NumGPRsUsed <= NumGPRs)
5691 continue;
5692 break;
5693 case MVT::v4i32:
5694 case MVT::v8i16:
5695 case MVT::v16i8:
5696 case MVT::v2f64:
5697 case MVT::v2i64:
5698 case MVT::v1i128:
5699 case MVT::f128:
5700 if (++NumVRsUsed <= NumVRs)
5701 continue;
5702 break;
5703 case MVT::v4f32:
5704 // When using QPX, this is handled like a FP register, otherwise, it
5705 // is an Altivec register.
5706 if (Subtarget.hasQPX()) {
5707 if (++NumFPRsUsed <= NumFPRs)
5708 continue;
5709 } else {
5710 if (++NumVRsUsed <= NumVRs)
5711 continue;
5712 }
5713 break;
5714 case MVT::f32:
5715 case MVT::f64:
5716 case MVT::v4f64: // QPX
5717 case MVT::v4i1: // QPX
5718 if (++NumFPRsUsed <= NumFPRs)
5719 continue;
5720 break;
5721 }
5722 HasParameterArea = true;
5723 }
5724 }
5725
5726 /* Respect alignment of argument on the stack. */
5727 unsigned Align =
5728 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5729 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5730
5731 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5732 if (Flags.isInConsecutiveRegsLast())
5733 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5734 }
5735
5736 unsigned NumBytesActuallyUsed = NumBytes;
5737
5738 // In the old ELFv1 ABI,
5739 // the prolog code of the callee may store up to 8 GPR argument registers to
5740 // the stack, allowing va_start to index over them in memory if its varargs.
5741 // Because we cannot tell if this is needed on the caller side, we have to
5742 // conservatively assume that it is needed. As such, make sure we have at
5743 // least enough stack space for the caller to store the 8 GPRs.
5744 // In the ELFv2 ABI, we allocate the parameter area iff a callee
5745 // really requires memory operands, e.g. a vararg function.
5746 if (HasParameterArea)
5747 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5748 else
5749 NumBytes = LinkageSize;
5750
5751 // Tail call needs the stack to be aligned.
5752 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5753 CallConv == CallingConv::Fast)
5754 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5755
5756 int SPDiff = 0;
5757
5758 // Calculate by how many bytes the stack has to be adjusted in case of tail
5759 // call optimization.
5760 if (!IsSibCall)
5761 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5762
5763 // To protect arguments on the stack from being clobbered in a tail call,
5764 // force all the loads to happen before doing any other lowering.
5765 if (isTailCall)
5766 Chain = DAG.getStackArgumentTokenFactor(Chain);
5767
5768 // Adjust the stack pointer for the new arguments...
5769 // These operations are automatically eliminated by the prolog/epilog pass
5770 if (!IsSibCall)
5771 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5772 SDValue CallSeqStart = Chain;
5773
5774 // Load the return address and frame pointer so it can be move somewhere else
5775 // later.
5776 SDValue LROp, FPOp;
5777 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5778
5779 // Set up a copy of the stack pointer for use loading and storing any
5780 // arguments that may not fit in the registers available for argument
5781 // passing.
5782 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5783
5784 // Figure out which arguments are going to go in registers, and which in
5785 // memory. Also, if this is a vararg function, floating point operations
5786 // must be stored to our stack, and loaded into integer regs as well, if
5787 // any integer regs are available for argument passing.
5788 unsigned ArgOffset = LinkageSize;
5789
5790 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5791 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5792
5793 SmallVector<SDValue, 8> MemOpChains;
5794 for (unsigned i = 0; i != NumOps; ++i) {
5795 SDValue Arg = OutVals[i];
5796 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5797 EVT ArgVT = Outs[i].VT;
5798 EVT OrigVT = Outs[i].ArgVT;
5799
5800 // PtrOff will be used to store the current argument to the stack if a
5801 // register cannot be found for it.
5802 SDValue PtrOff;
5803
5804 // We re-align the argument offset for each argument, except when using the
5805 // fast calling convention, when we need to make sure we do that only when
5806 // we'll actually use a stack slot.
5807 auto ComputePtrOff = [&]() {
5808 /* Respect alignment of argument on the stack. */
5809 unsigned Align =
5810 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5811 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5812
5813 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5814
5815 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5816 };
5817
5818 if (CallConv != CallingConv::Fast) {
5819 ComputePtrOff();
5820
5821 /* Compute GPR index associated with argument offset. */
5822 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5823 GPR_idx = std::min(GPR_idx, NumGPRs);
5824 }
5825
5826 // Promote integers to 64-bit values.
5827 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5828 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5829 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5830 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5831 }
5832
5833 // FIXME memcpy is used way more than necessary. Correctness first.
5834 // Note: "by value" is code for passing a structure by value, not
5835 // basic types.
5836 if (Flags.isByVal()) {
5837 // Note: Size includes alignment padding, so
5838 // struct x { short a; char b; }
5839 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
5840 // These are the proper values we need for right-justifying the
5841 // aggregate in a parameter register.
5842 unsigned Size = Flags.getByValSize();
5843
5844 // An empty aggregate parameter takes up no storage and no
5845 // registers.
5846 if (Size == 0)
5847 continue;
5848
5849 if (CallConv == CallingConv::Fast)
5850 ComputePtrOff();
5851
5852 // All aggregates smaller than 8 bytes must be passed right-justified.
5853 if (Size==1 || Size==2 || Size==4) {
5854 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5855 if (GPR_idx != NumGPRs) {
5856 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5857 MachinePointerInfo(), VT);
5858 MemOpChains.push_back(Load.getValue(1));
5859 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5860
5861 ArgOffset += PtrByteSize;
5862 continue;
5863 }
5864 }
5865
5866 if (GPR_idx == NumGPRs && Size < 8) {
5867 SDValue AddPtr = PtrOff;
5868 if (!isLittleEndian) {
5869 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5870 PtrOff.getValueType());
5871 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5872 }
5873 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5874 CallSeqStart,
5875 Flags, DAG, dl);
5876 ArgOffset += PtrByteSize;
5877 continue;
5878 }
5879 // Copy entire object into memory. There are cases where gcc-generated
5880 // code assumes it is there, even if it could be put entirely into
5881 // registers. (This is not what the doc says.)
5882
5883 // FIXME: The above statement is likely due to a misunderstanding of the
5884 // documents. All arguments must be copied into the parameter area BY
5885 // THE CALLEE in the event that the callee takes the address of any
5886 // formal argument. That has not yet been implemented. However, it is
5887 // reasonable to use the stack area as a staging area for the register
5888 // load.
5889
5890 // Skip this for small aggregates, as we will use the same slot for a
5891 // right-justified copy, below.
5892 if (Size >= 8)
5893 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5894 CallSeqStart,
5895 Flags, DAG, dl);
5896
5897 // When a register is available, pass a small aggregate right-justified.
5898 if (Size < 8 && GPR_idx != NumGPRs) {
5899 // The easiest way to get this right-justified in a register
5900 // is to copy the structure into the rightmost portion of a
5901 // local variable slot, then load the whole slot into the
5902 // register.
5903 // FIXME: The memcpy seems to produce pretty awful code for
5904 // small aggregates, particularly for packed ones.
5905 // FIXME: It would be preferable to use the slot in the
5906 // parameter save area instead of a new local variable.
5907 SDValue AddPtr = PtrOff;
5908 if (!isLittleEndian) {
5909 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5910 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5911 }
5912 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5913 CallSeqStart,
5914 Flags, DAG, dl);
5915
5916 // Load the slot into the register.
5917 SDValue Load =
5918 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5919 MemOpChains.push_back(Load.getValue(1));
5920 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5921
5922 // Done with this argument.
5923 ArgOffset += PtrByteSize;
5924 continue;
5925 }
5926
5927 // For aggregates larger than PtrByteSize, copy the pieces of the
5928 // object that fit into registers from the parameter save area.
5929 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5930 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5931 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5932 if (GPR_idx != NumGPRs) {
5933 SDValue Load =
5934 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5935 MemOpChains.push_back(Load.getValue(1));
5936 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5937 ArgOffset += PtrByteSize;
5938 } else {
5939 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5940 break;
5941 }
5942 }
5943 continue;
5944 }
5945
5946 switch (Arg.getSimpleValueType().SimpleTy) {
5947 default: llvm_unreachable("Unexpected ValueType for argument!");
5948 case MVT::i1:
5949 case MVT::i32:
5950 case MVT::i64:
5951 if (Flags.isNest()) {
5952 // The 'nest' parameter, if any, is passed in R11.
5953 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5954 hasNest = true;
5955 break;
5956 }
5957
5958 // These can be scalar arguments or elements of an integer array type
5959 // passed directly. Clang may use those instead of "byval" aggregate
5960 // types to avoid forcing arguments to memory unnecessarily.
5961 if (GPR_idx != NumGPRs) {
5962 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5963 } else {
5964 if (CallConv == CallingConv::Fast)
5965 ComputePtrOff();
5966
5967 assert(HasParameterArea &&
5968 "Parameter area must exist to pass an argument in memory.");
5969 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5970 true, isTailCall, false, MemOpChains,
5971 TailCallArguments, dl);
5972 if (CallConv == CallingConv::Fast)
5973 ArgOffset += PtrByteSize;
5974 }
5975 if (CallConv != CallingConv::Fast)
5976 ArgOffset += PtrByteSize;
5977 break;
5978 case MVT::f32:
5979 case MVT::f64: {
5980 // These can be scalar arguments or elements of a float array type
5981 // passed directly. The latter are used to implement ELFv2 homogenous
5982 // float aggregates.
5983
5984 // Named arguments go into FPRs first, and once they overflow, the
5985 // remaining arguments go into GPRs and then the parameter save area.
5986 // Unnamed arguments for vararg functions always go to GPRs and
5987 // then the parameter save area. For now, put all arguments to vararg
5988 // routines always in both locations (FPR *and* GPR or stack slot).
5989 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5990 bool NeededLoad = false;
5991
5992 // First load the argument into the next available FPR.
5993 if (FPR_idx != NumFPRs)
5994 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5995
5996 // Next, load the argument into GPR or stack slot if needed.
5997 if (!NeedGPROrStack)
5998 ;
5999 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
6000 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6001 // once we support fp <-> gpr moves.
6002
6003 // In the non-vararg case, this can only ever happen in the
6004 // presence of f32 array types, since otherwise we never run
6005 // out of FPRs before running out of GPRs.
6006 SDValue ArgVal;
6007
6008 // Double values are always passed in a single GPR.
6009 if (Arg.getValueType() != MVT::f32) {
6010 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6011
6012 // Non-array float values are extended and passed in a GPR.
6013 } else if (!Flags.isInConsecutiveRegs()) {
6014 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6015 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6016
6017 // If we have an array of floats, we collect every odd element
6018 // together with its predecessor into one GPR.
6019 } else if (ArgOffset % PtrByteSize != 0) {
6020 SDValue Lo, Hi;
6021 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6022 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6023 if (!isLittleEndian)
6024 std::swap(Lo, Hi);
6025 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6026
6027 // The final element, if even, goes into the first half of a GPR.
6028 } else if (Flags.isInConsecutiveRegsLast()) {
6029 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6030 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6031 if (!isLittleEndian)
6032 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6033 DAG.getConstant(32, dl, MVT::i32));
6034
6035 // Non-final even elements are skipped; they will be handled
6036 // together the with subsequent argument on the next go-around.
6037 } else
6038 ArgVal = SDValue();
6039
6040 if (ArgVal.getNode())
6041 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6042 } else {
6043 if (CallConv == CallingConv::Fast)
6044 ComputePtrOff();
6045
6046 // Single-precision floating-point values are mapped to the
6047 // second (rightmost) word of the stack doubleword.
6048 if (Arg.getValueType() == MVT::f32 &&
6049 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6050 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6051 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6052 }
6053
6054 assert(HasParameterArea &&
6055 "Parameter area must exist to pass an argument in memory.");
6056 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6057 true, isTailCall, false, MemOpChains,
6058 TailCallArguments, dl);
6059
6060 NeededLoad = true;
6061 }
6062 // When passing an array of floats, the array occupies consecutive
6063 // space in the argument area; only round up to the next doubleword
6064 // at the end of the array. Otherwise, each float takes 8 bytes.
6065 if (CallConv != CallingConv::Fast || NeededLoad) {
6066 ArgOffset += (Arg.getValueType() == MVT::f32 &&
6067 Flags.isInConsecutiveRegs()) ? 4 : 8;
6068 if (Flags.isInConsecutiveRegsLast())
6069 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6070 }
6071 break;
6072 }
6073 case MVT::v4f32:
6074 case MVT::v4i32:
6075 case MVT::v8i16:
6076 case MVT::v16i8:
6077 case MVT::v2f64:
6078 case MVT::v2i64:
6079 case MVT::v1i128:
6080 case MVT::f128:
6081 if (!Subtarget.hasQPX()) {
6082 // These can be scalar arguments or elements of a vector array type
6083 // passed directly. The latter are used to implement ELFv2 homogenous
6084 // vector aggregates.
6085
6086 // For a varargs call, named arguments go into VRs or on the stack as
6087 // usual; unnamed arguments always go to the stack or the corresponding
6088 // GPRs when within range. For now, we always put the value in both
6089 // locations (or even all three).
6090 if (isVarArg) {
6091 assert(HasParameterArea &&
6092 "Parameter area must exist if we have a varargs call.");
6093 // We could elide this store in the case where the object fits
6094 // entirely in R registers. Maybe later.
6095 SDValue Store =
6096 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6097 MemOpChains.push_back(Store);
6098 if (VR_idx != NumVRs) {
6099 SDValue Load =
6100 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6101 MemOpChains.push_back(Load.getValue(1));
6102 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6103 }
6104 ArgOffset += 16;
6105 for (unsigned i=0; i<16; i+=PtrByteSize) {
6106 if (GPR_idx == NumGPRs)
6107 break;
6108 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6109 DAG.getConstant(i, dl, PtrVT));
6110 SDValue Load =
6111 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6112 MemOpChains.push_back(Load.getValue(1));
6113 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6114 }
6115 break;
6116 }
6117
6118 // Non-varargs Altivec params go into VRs or on the stack.
6119 if (VR_idx != NumVRs) {
6120 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6121 } else {
6122 if (CallConv == CallingConv::Fast)
6123 ComputePtrOff();
6124
6125 assert(HasParameterArea &&
6126 "Parameter area must exist to pass an argument in memory.");
6127 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6128 true, isTailCall, true, MemOpChains,
6129 TailCallArguments, dl);
6130 if (CallConv == CallingConv::Fast)
6131 ArgOffset += 16;
6132 }
6133
6134 if (CallConv != CallingConv::Fast)
6135 ArgOffset += 16;
6136 break;
6137 } // not QPX
6138
6139 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6140 "Invalid QPX parameter type");
6141
6142 LLVM_FALLTHROUGH;
6143 case MVT::v4f64:
6144 case MVT::v4i1: {
6145 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6146 if (isVarArg) {
6147 assert(HasParameterArea &&
6148 "Parameter area must exist if we have a varargs call.");
6149 // We could elide this store in the case where the object fits
6150 // entirely in R registers. Maybe later.
6151 SDValue Store =
6152 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6153 MemOpChains.push_back(Store);
6154 if (QFPR_idx != NumQFPRs) {
6155 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6156 PtrOff, MachinePointerInfo());
6157 MemOpChains.push_back(Load.getValue(1));
6158 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6159 }
6160 ArgOffset += (IsF32 ? 16 : 32);
6161 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6162 if (GPR_idx == NumGPRs)
6163 break;
6164 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6165 DAG.getConstant(i, dl, PtrVT));
6166 SDValue Load =
6167 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6168 MemOpChains.push_back(Load.getValue(1));
6169 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6170 }
6171 break;
6172 }
6173
6174 // Non-varargs QPX params go into registers or on the stack.
6175 if (QFPR_idx != NumQFPRs) {
6176 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6177 } else {
6178 if (CallConv == CallingConv::Fast)
6179 ComputePtrOff();
6180
6181 assert(HasParameterArea &&
6182 "Parameter area must exist to pass an argument in memory.");
6183 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6184 true, isTailCall, true, MemOpChains,
6185 TailCallArguments, dl);
6186 if (CallConv == CallingConv::Fast)
6187 ArgOffset += (IsF32 ? 16 : 32);
6188 }
6189
6190 if (CallConv != CallingConv::Fast)
6191 ArgOffset += (IsF32 ? 16 : 32);
6192 break;
6193 }
6194 }
6195 }
6196
6197 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6198 "mismatch in size of parameter area");
6199 (void)NumBytesActuallyUsed;
6200
6201 if (!MemOpChains.empty())
6202 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6203
6204 // Check if this is an indirect call (MTCTR/BCTRL).
6205 // See PrepareCall() for more information about calls through function
6206 // pointers in the 64-bit SVR4 ABI.
6207 if (!isTailCall && !isPatchPoint &&
6208 !isFunctionGlobalAddress(Callee) &&
6209 !isa<ExternalSymbolSDNode>(Callee)) {
6210 // Load r2 into a virtual register and store it to the TOC save area.
6211 setUsesTOCBasePtr(DAG);
6212 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6213 // TOC save area offset.
6214 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6215 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6216 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6217 Chain = DAG.getStore(
6218 Val.getValue(1), dl, Val, AddPtr,
6219 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6220 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6221 // This does not mean the MTCTR instruction must use R12; it's easier
6222 // to model this as an extra parameter, so do that.
6223 if (isELFv2ABI && !isPatchPoint)
6224 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6225 }
6226
6227 // Build a sequence of copy-to-reg nodes chained together with token chain
6228 // and flag operands which copy the outgoing args into the appropriate regs.
6229 SDValue InFlag;
6230 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6231 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6232 RegsToPass[i].second, InFlag);
6233 InFlag = Chain.getValue(1);
6234 }
6235
6236 if (isTailCall && !IsSibCall)
6237 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6238 TailCallArguments);
6239
6240 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6241 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6242 SPDiff, NumBytes, Ins, InVals, CS);
6243}
6244
6245SDValue PPCTargetLowering::LowerCall_Darwin(
6246 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6247 bool isTailCall, bool isPatchPoint,
6248 const SmallVectorImpl<ISD::OutputArg> &Outs,
6249 const SmallVectorImpl<SDValue> &OutVals,
6250 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6251 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6252 ImmutableCallSite CS) const {
6253 unsigned NumOps = Outs.size();
6254
6255 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6256 bool isPPC64 = PtrVT == MVT::i64;
6257 unsigned PtrByteSize = isPPC64 ? 8 : 4;
6258
6259 MachineFunction &MF = DAG.getMachineFunction();
6260
6261 // Mark this function as potentially containing a function that contains a
6262 // tail call. As a consequence the frame pointer will be used for dynamicalloc
6263 // and restoring the callers stack pointer in this functions epilog. This is
6264 // done because by tail calling the called function might overwrite the value
6265 // in this function's (MF) stack pointer stack slot 0(SP).
6266 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6267 CallConv == CallingConv::Fast)
6268 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6269
6270 // Count how many bytes are to be pushed on the stack, including the linkage
6271 // area, and parameter passing area. We start with 24/48 bytes, which is
6272 // prereserved space for [SP][CR][LR][3 x unused].
6273 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6274 unsigned NumBytes = LinkageSize;
6275
6276 // Add up all the space actually used.
6277 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6278 // they all go in registers, but we must reserve stack space for them for
6279 // possible use by the caller. In varargs or 64-bit calls, parameters are
6280 // assigned stack space in order, with padding so Altivec parameters are
6281 // 16-byte aligned.
6282 unsigned nAltivecParamsAtEnd = 0;
6283 for (unsigned i = 0; i != NumOps; ++i) {
6284 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6285 EVT ArgVT = Outs[i].VT;
6286 // Varargs Altivec parameters are padded to a 16 byte boundary.
6287 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6288 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6289 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6290 if (!isVarArg && !isPPC64) {
6291 // Non-varargs Altivec parameters go after all the non-Altivec
6292 // parameters; handle those later so we know how much padding we need.
6293 nAltivecParamsAtEnd++;
6294 continue;
6295 }
6296 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6297 NumBytes = ((NumBytes+15)/16)*16;
6298 }
6299 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6300 }
6301
6302 // Allow for Altivec parameters at the end, if needed.
6303 if (nAltivecParamsAtEnd) {
6304 NumBytes = ((NumBytes+15)/16)*16;
6305 NumBytes += 16*nAltivecParamsAtEnd;
6306 }
6307
6308 // The prolog code of the callee may store up to 8 GPR argument registers to
6309 // the stack, allowing va_start to index over them in memory if its varargs.
6310 // Because we cannot tell if this is needed on the caller side, we have to
6311 // conservatively assume that it is needed. As such, make sure we have at
6312 // least enough stack space for the caller to store the 8 GPRs.
6313 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6314
6315 // Tail call needs the stack to be aligned.
6316 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6317 CallConv == CallingConv::Fast)
6318 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6319
6320 // Calculate by how many bytes the stack has to be adjusted in case of tail
6321 // call optimization.
6322 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6323
6324 // To protect arguments on the stack from being clobbered in a tail call,
6325 // force all the loads to happen before doing any other lowering.
6326 if (isTailCall)
6327 Chain = DAG.getStackArgumentTokenFactor(Chain);
6328
6329 // Adjust the stack pointer for the new arguments...
6330 // These operations are automatically eliminated by the prolog/epilog pass
6331 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6332 SDValue CallSeqStart = Chain;
6333
6334 // Load the return address and frame pointer so it can be move somewhere else
6335 // later.
6336 SDValue LROp, FPOp;
6337 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6338
6339 // Set up a copy of the stack pointer for use loading and storing any
6340 // arguments that may not fit in the registers available for argument
6341 // passing.
6342 SDValue StackPtr;
6343 if (isPPC64)
6344 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6345 else
6346 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6347
6348 // Figure out which arguments are going to go in registers, and which in
6349 // memory. Also, if this is a vararg function, floating point operations
6350 // must be stored to our stack, and loaded into integer regs as well, if
6351 // any integer regs are available for argument passing.
6352 unsigned ArgOffset = LinkageSize;
6353 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6354
6355 static const MCPhysReg GPR_32[] = { // 32-bit registers.
6356 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6357 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6358 };
6359 static const MCPhysReg GPR_64[] = { // 64-bit registers.
6360 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6361 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6362 };
6363 static const MCPhysReg VR[] = {
6364 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6365 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6366 };
6367 const unsigned NumGPRs = array_lengthof(GPR_32);
6368 const unsigned NumFPRs = 13;
6369 const unsigned NumVRs = array_lengthof(VR);
6370
6371 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6372
6373 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6374 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6375
6376 SmallVector<SDValue, 8> MemOpChains;
6377 for (unsigned i = 0; i != NumOps; ++i) {
6378 SDValue Arg = OutVals[i];
6379 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6380
6381 // PtrOff will be used to store the current argument to the stack if a
6382 // register cannot be found for it.
6383 SDValue PtrOff;
6384
6385 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6386
6387 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6388
6389 // On PPC64, promote integers to 64-bit values.
6390 if (isPPC64 && Arg.getValueType() == MVT::i32) {
6391 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6392 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6393 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6394 }
6395
6396 // FIXME memcpy is used way more than necessary. Correctness first.
6397 // Note: "by value" is code for passing a structure by value, not
6398 // basic types.
6399 if (Flags.isByVal()) {
6400 unsigned Size = Flags.getByValSize();
6401 // Very small objects are passed right-justified. Everything else is
6402 // passed left-justified.
6403 if (Size==1 || Size==2) {
6404 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6405 if (GPR_idx != NumGPRs) {
6406 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6407 MachinePointerInfo(), VT);
6408 MemOpChains.push_back(Load.getValue(1));
6409 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6410
6411 ArgOffset += PtrByteSize;
6412 } else {
6413 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6414 PtrOff.getValueType());
6415 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6416 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6417 CallSeqStart,
6418 Flags, DAG, dl);
6419 ArgOffset += PtrByteSize;
6420 }
6421 continue;
6422 }
6423 // Copy entire object into memory. There are cases where gcc-generated
6424 // code assumes it is there, even if it could be put entirely into
6425 // registers. (This is not what the doc says.)
6426 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6427 CallSeqStart,
6428 Flags, DAG, dl);
6429
6430 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6431 // copy the pieces of the object that fit into registers from the
6432 // parameter save area.
6433 for (unsigned j=0; j<Size; j+=PtrByteSize) {
6434 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6435 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6436 if (GPR_idx != NumGPRs) {
6437 SDValue Load =
6438 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6439 MemOpChains.push_back(Load.getValue(1));
6440 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6441 ArgOffset += PtrByteSize;
6442 } else {
6443 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6444 break;
6445 }
6446 }
6447 continue;
6448 }
6449
6450 switch (Arg.getSimpleValueType().SimpleTy) {
6451 default: llvm_unreachable("Unexpected ValueType for argument!");
6452 case MVT::i1:
6453 case MVT::i32:
6454 case MVT::i64:
6455 if (GPR_idx != NumGPRs) {
6456 if (Arg.getValueType() == MVT::i1)
6457 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6458
6459 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6460 } else {
6461 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6462 isPPC64, isTailCall, false, MemOpChains,
6463 TailCallArguments, dl);
6464 }
6465 ArgOffset += PtrByteSize;
6466 break;
6467 case MVT::f32:
6468 case MVT::f64:
6469 if (FPR_idx != NumFPRs) {
6470 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6471
6472 if (isVarArg) {
6473 SDValue Store =
6474 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6475 MemOpChains.push_back(Store);
6476
6477 // Float varargs are always shadowed in available integer registers
6478 if (GPR_idx != NumGPRs) {
6479 SDValue Load =
6480 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6481 MemOpChains.push_back(Load.getValue(1));
6482 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6483 }
6484 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6485 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6486 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6487 SDValue Load =
6488 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6489 MemOpChains.push_back(Load.getValue(1));
6490 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6491 }
6492 } else {
6493 // If we have any FPRs remaining, we may also have GPRs remaining.
6494 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6495 // GPRs.
6496 if (GPR_idx != NumGPRs)
6497 ++GPR_idx;
6498 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6499 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
6500 ++GPR_idx;
6501 }
6502 } else
6503 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6504 isPPC64, isTailCall, false, MemOpChains,
6505 TailCallArguments, dl);
6506 if (isPPC64)
6507 ArgOffset += 8;
6508 else
6509 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6510 break;
6511 case MVT::v4f32:
6512 case MVT::v4i32:
6513 case MVT::v8i16:
6514 case MVT::v16i8:
6515 if (isVarArg) {
6516 // These go aligned on the stack, or in the corresponding R registers
6517 // when within range. The Darwin PPC ABI doc claims they also go in
6518 // V registers; in fact gcc does this only for arguments that are
6519 // prototyped, not for those that match the ... We do it for all
6520 // arguments, seems to work.
6521 while (ArgOffset % 16 !=0) {
6522 ArgOffset += PtrByteSize;
6523 if (GPR_idx != NumGPRs)
6524 GPR_idx++;
6525 }
6526 // We could elide this store in the case where the object fits
6527 // entirely in R registers. Maybe later.
6528 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6529 DAG.getConstant(ArgOffset, dl, PtrVT));
6530 SDValue Store =
6531 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6532 MemOpChains.push_back(Store);
6533 if (VR_idx != NumVRs) {
6534 SDValue Load =
6535 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6536 MemOpChains.push_back(Load.getValue(1));
6537 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6538 }
6539 ArgOffset += 16;
6540 for (unsigned i=0; i<16; i+=PtrByteSize) {
6541 if (GPR_idx == NumGPRs)
6542 break;
6543 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6544 DAG.getConstant(i, dl, PtrVT));
6545 SDValue Load =
6546 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6547 MemOpChains.push_back(Load.getValue(1));
6548 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6549 }
6550 break;
6551 }
6552
6553 // Non-varargs Altivec params generally go in registers, but have
6554 // stack space allocated at the end.
6555 if (VR_idx != NumVRs) {
6556 // Doesn't have GPR space allocated.
6557 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6558 } else if (nAltivecParamsAtEnd==0) {
6559 // We are emitting Altivec params in order.
6560 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6561 isPPC64, isTailCall, true, MemOpChains,
6562 TailCallArguments, dl);
6563 ArgOffset += 16;
6564 }
6565 break;
6566 }
6567 }
6568 // If all Altivec parameters fit in registers, as they usually do,
6569 // they get stack space following the non-Altivec parameters. We
6570 // don't track this here because nobody below needs it.
6571 // If there are more Altivec parameters than fit in registers emit
6572 // the stores here.
6573 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6574 unsigned j = 0;
6575 // Offset is aligned; skip 1st 12 params which go in V registers.
6576 ArgOffset = ((ArgOffset+15)/16)*16;
6577 ArgOffset += 12*16;
6578 for (unsigned i = 0; i != NumOps; ++i) {
6579 SDValue Arg = OutVals[i];
6580 EVT ArgType = Outs[i].VT;
6581 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6582 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6583 if (++j > NumVRs) {
6584 SDValue PtrOff;
6585 // We are emitting Altivec params in order.
6586 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6587 isPPC64, isTailCall, true, MemOpChains,
6588 TailCallArguments, dl);
6589 ArgOffset += 16;
6590 }
6591 }
6592 }
6593 }
6594
6595 if (!MemOpChains.empty())
6596 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6597
6598 // On Darwin, R12 must contain the address of an indirect callee. This does
6599 // not mean the MTCTR instruction must use R12; it's easier to model this as
6600 // an extra parameter, so do that.
6601 if (!isTailCall &&
6602 !isFunctionGlobalAddress(Callee) &&
6603 !isa<ExternalSymbolSDNode>(Callee) &&
6604 !isBLACompatibleAddress(Callee, DAG))
6605 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6606 PPC::R12), Callee));
6607
6608 // Build a sequence of copy-to-reg nodes chained together with token chain
6609 // and flag operands which copy the outgoing args into the appropriate regs.
6610 SDValue InFlag;
6611 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6612 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6613 RegsToPass[i].second, InFlag);
6614 InFlag = Chain.getValue(1);
6615 }
6616
6617 if (isTailCall)
6618 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6619 TailCallArguments);
6620
6621 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6622 /* unused except on PPC64 ELFv1 */ false, DAG,
6623 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6624 NumBytes, Ins, InVals, CS);
6625}
6626
6627
6628SDValue PPCTargetLowering::LowerCall_AIX(
6629 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6630 bool isTailCall, bool isPatchPoint,
6631 const SmallVectorImpl<ISD::OutputArg> &Outs,
6632 const SmallVectorImpl<SDValue> &OutVals,
6633 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6634 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6635 ImmutableCallSite CS) const {
6636
6637 assert((CallConv == CallingConv::C || CallConv == CallingConv::Fast) &&
6638 "Unimplemented calling convention!");
6639 if (isVarArg || isPatchPoint)
6640 report_fatal_error("This call type is unimplemented on AIX.");
6641
6642 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6643 bool isPPC64 = PtrVT == MVT::i64;
6644 unsigned PtrByteSize = isPPC64 ? 8 : 4;
6645 unsigned NumOps = Outs.size();
6646
6647
6648 // Count how many bytes are to be pushed on the stack, including the linkage
6649 // area, parameter list area.
6650 // On XCOFF, we start with 24/48, which is reserved space for
6651 // [SP][CR][LR][2 x reserved][TOC].
6652 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6653
6654 // The prolog code of the callee may store up to 8 GPR argument registers to
6655 // the stack, allowing va_start to index over them in memory if the callee
6656 // is variadic.
6657 // Because we cannot tell if this is needed on the caller side, we have to
6658 // conservatively assume that it is needed. As such, make sure we have at
6659 // least enough stack space for the caller to store the 8 GPRs.
6660 unsigned NumBytes = LinkageSize + 8 * PtrByteSize;
6661
6662 // Adjust the stack pointer for the new arguments...
6663 // These operations are automatically eliminated by the prolog/epilog
6664 // inserter pass.
6665 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6666 SDValue CallSeqStart = Chain;
6667
6668 static const MCPhysReg GPR_32[] = { // 32-bit registers.
6669 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6670 PPC::R7, PPC::R8, PPC::R9, PPC::R10
6671 };
6672 static const MCPhysReg GPR_64[] = { // 64-bit registers.
6673 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6674 PPC::X7, PPC::X8, PPC::X9, PPC::X10
6675 };
6676
6677 const unsigned NumGPRs = isPPC64 ? array_lengthof(GPR_64)
6678 : array_lengthof(GPR_32);
6679 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6680 unsigned GPR_idx = 0;
6681
6682 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6683
6684 if (isTailCall)
6685 report_fatal_error("Handling of tail call is unimplemented!");
6686 int SPDiff = 0;
6687
6688 for (unsigned i = 0; i != NumOps; ++i) {
6689 SDValue Arg = OutVals[i];
6690 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6691
6692 // Promote integers if needed.
6693 if (Arg.getValueType() == MVT::i1 ||
6694 (isPPC64 && Arg.getValueType() == MVT::i32)) {
6695 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6696 Arg = DAG.getNode(ExtOp, dl, PtrVT, Arg);
6697 }
6698
6699 // Note: "by value" is code for passing a structure by value, not
6700 // basic types.
6701 if (Flags.isByVal())
6702 report_fatal_error("Passing structure by value is unimplemented!");
6703
6704 switch (Arg.getSimpleValueType().SimpleTy) {
6705 default: llvm_unreachable("Unexpected ValueType for argument!");
6706 case MVT::i1:
6707 case MVT::i32:
6708 case MVT::i64:
6709 if (GPR_idx != NumGPRs)
6710 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6711 else
6712 report_fatal_error("Handling of placing parameters on the stack is "
6713 "unimplemented!");
6714 break;
6715 case MVT::f32:
6716 case MVT::f64:
6717 case MVT::v4f32:
6718 case MVT::v4i32:
6719 case MVT::v8i16:
6720 case MVT::v16i8:
6721 case MVT::v2f64:
6722 case MVT::v2i64:
6723 case MVT::v1i128:
6724 case MVT::f128:
6725 case MVT::v4f64:
6726 case MVT::v4i1:
6727 report_fatal_error("Handling of this parameter type is unimplemented!");
6728 }
6729 }
6730
6731 if (!isFunctionGlobalAddress(Callee) &&
6732 !isa<ExternalSymbolSDNode>(Callee))
6733 report_fatal_error("Handling of indirect call is unimplemented!");
6734
6735 // Build a sequence of copy-to-reg nodes chained together with token chain
6736 // and flag operands which copy the outgoing args into the appropriate regs.
6737 SDValue InFlag;
6738 for (auto Reg : RegsToPass) {
6739 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
6740 InFlag = Chain.getValue(1);
6741 }
6742
6743 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6744 /* unused except on PPC64 ELFv1 */ false, DAG,
6745 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6746 NumBytes, Ins, InVals, CS);
6747}
6748
6749bool
6750PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6751 MachineFunction &MF, bool isVarArg,
6752 const SmallVectorImpl<ISD::OutputArg> &Outs,
6753 LLVMContext &Context) const {
6754 SmallVector<CCValAssign, 16> RVLocs;
6755 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6756 return CCInfo.CheckReturn(
6757 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6758 ? RetCC_PPC_Cold
6759 : RetCC_PPC);
6760}
6761
6762SDValue
6763PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6764 bool isVarArg,
6765 const SmallVectorImpl<ISD::OutputArg> &Outs,
6766 const SmallVectorImpl<SDValue> &OutVals,
6767 const SDLoc &dl, SelectionDAG &DAG) const {
6768 SmallVector<CCValAssign, 16> RVLocs;
6769 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6770 *DAG.getContext());
6771 CCInfo.AnalyzeReturn(Outs,
6772 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6773 ? RetCC_PPC_Cold
6774 : RetCC_PPC);
6775
6776 SDValue Flag;
6777 SmallVector<SDValue, 4> RetOps(1, Chain);
6778
6779 // Copy the result values into the output registers.
6780 for (unsigned i = 0; i != RVLocs.size(); ++i) {
6781 CCValAssign &VA = RVLocs[i];
6782 assert(VA.isRegLoc() && "Can only return in registers!");
6783
6784 SDValue Arg = OutVals[i];
6785
6786 switch (VA.getLocInfo()) {
6787 default: llvm_unreachable("Unknown loc info!");
6788 case CCValAssign::Full: break;
6789 case CCValAssign::AExt:
6790 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6791 break;
6792 case CCValAssign::ZExt:
6793 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6794 break;
6795 case CCValAssign::SExt:
6796 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6797 break;
6798 }
6799
6800 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6801 Flag = Chain.getValue(1);
6802 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6803 }
6804
6805 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6806 const MCPhysReg *I =
6807 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6808 if (I) {
6809 for (; *I; ++I) {
6810
6811 if (PPC::G8RCRegClass.contains(*I))
6812 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6813 else if (PPC::F8RCRegClass.contains(*I))
6814 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6815 else if (PPC::CRRCRegClass.contains(*I))
6816 RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6817 else if (PPC::VRRCRegClass.contains(*I))
6818 RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6819 else
6820 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6821 }
6822 }
6823
6824 RetOps[0] = Chain; // Update chain.
6825
6826 // Add the flag if we have it.
6827 if (Flag.getNode())
6828 RetOps.push_back(Flag);
6829
6830 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6831}
6832
6833SDValue
6834PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6835 SelectionDAG &DAG) const {
6836 SDLoc dl(Op);
6837
6838 // Get the correct type for integers.
6839 EVT IntVT = Op.getValueType();
6840
6841 // Get the inputs.
6842 SDValue Chain = Op.getOperand(0);
6843 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6844 // Build a DYNAREAOFFSET node.
6845 SDValue Ops[2] = {Chain, FPSIdx};
6846 SDVTList VTs = DAG.getVTList(IntVT);
6847 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6848}
6849
6850SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6851 SelectionDAG &DAG) const {
6852 // When we pop the dynamic allocation we need to restore the SP link.
6853 SDLoc dl(Op);
6854
6855 // Get the correct type for pointers.
6856 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6857
6858 // Construct the stack pointer operand.
6859 bool isPPC64 = Subtarget.isPPC64();
6860 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6861 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6862
6863 // Get the operands for the STACKRESTORE.
6864 SDValue Chain = Op.getOperand(0);
6865 SDValue SaveSP = Op.getOperand(1);
6866
6867 // Load the old link SP.
6868 SDValue LoadLinkSP =
6869 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6870
6871 // Restore the stack pointer.
6872 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6873
6874 // Store the old link SP.
6875 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6876}
6877
6878SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6879 MachineFunction &MF = DAG.getMachineFunction();
6880 bool isPPC64 = Subtarget.isPPC64();
6881 EVT PtrVT = getPointerTy(MF.getDataLayout());
6882
6883 // Get current frame pointer save index. The users of this index will be
6884 // primarily DYNALLOC instructions.
6885 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6886 int RASI = FI->getReturnAddrSaveIndex();
6887
6888 // If the frame pointer save index hasn't been defined yet.
6889 if (!RASI) {
6890 // Find out what the fix offset of the frame pointer save area.
6891 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6892 // Allocate the frame index for frame pointer save area.
6893 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6894 // Save the result.
6895 FI->setReturnAddrSaveIndex(RASI);
6896 }
6897 return DAG.getFrameIndex(RASI, PtrVT);
6898}
6899
6900SDValue
6901PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6902 MachineFunction &MF = DAG.getMachineFunction();
6903 bool isPPC64 = Subtarget.isPPC64();
6904 EVT PtrVT = getPointerTy(MF.getDataLayout());
6905
6906 // Get current frame pointer save index. The users of this index will be
6907 // primarily DYNALLOC instructions.
6908 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6909 int FPSI = FI->getFramePointerSaveIndex();
6910
6911 // If the frame pointer save index hasn't been defined yet.
6912 if (!FPSI) {
6913 // Find out what the fix offset of the frame pointer save area.
6914 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6915 // Allocate the frame index for frame pointer save area.
6916 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6917 // Save the result.
6918 FI->setFramePointerSaveIndex(FPSI);
6919 }
6920 return DAG.getFrameIndex(FPSI, PtrVT);
6921}
6922
6923SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6924 SelectionDAG &DAG) const {
6925 // Get the inputs.
6926 SDValue Chain = Op.getOperand(0);
6927 SDValue Size = Op.getOperand(1);
6928 SDLoc dl(Op);
6929
6930 // Get the correct type for pointers.
6931 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6932 // Negate the size.
6933 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6934 DAG.getConstant(0, dl, PtrVT), Size);
6935 // Construct a node for the frame pointer save index.
6936 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6937 // Build a DYNALLOC node.
6938 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6939 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6940 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6941}
6942
6943SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6944 SelectionDAG &DAG) const {
6945 MachineFunction &MF = DAG.getMachineFunction();
6946
6947 bool isPPC64 = Subtarget.isPPC64();
6948 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6949
6950 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6951 return DAG.getFrameIndex(FI, PtrVT);
6952}
6953
6954SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6955 SelectionDAG &DAG) const {
6956 SDLoc DL(Op);
6957 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6958 DAG.getVTList(MVT::i32, MVT::Other),
6959 Op.getOperand(0), Op.getOperand(1));
6960}
6961
6962SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6963 SelectionDAG &DAG) const {
6964 SDLoc DL(Op);
6965 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6966 Op.getOperand(0), Op.getOperand(1));
6967}
6968
6969SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6970 if (Op.getValueType().isVector())
6971 return LowerVectorLoad(Op, DAG);
6972
6973 assert(Op.getValueType() == MVT::i1 &&
6974 "Custom lowering only for i1 loads");
6975
6976 // First, load 8 bits into 32 bits, then truncate to 1 bit.
6977
6978 SDLoc dl(Op);
6979 LoadSDNode *LD = cast<LoadSDNode>(Op);
6980
6981 SDValue Chain = LD->getChain();
6982 SDValue BasePtr = LD->getBasePtr();
6983 MachineMemOperand *MMO = LD->getMemOperand();
6984
6985 SDValue NewLD =
6986 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6987 BasePtr, MVT::i8, MMO);
6988 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6989
6990 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6991 return DAG.getMergeValues(Ops, dl);
6992}
6993
6994SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6995 if (Op.getOperand(1).getValueType().isVector())
6996 return LowerVectorStore(Op, DAG);
6997
6998 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6999 "Custom lowering only for i1 stores");
7000
7001 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7002
7003 SDLoc dl(Op);
7004 StoreSDNode *ST = cast<StoreSDNode>(Op);
7005
7006 SDValue Chain = ST->getChain();
7007 SDValue BasePtr = ST->getBasePtr();
7008 SDValue Value = ST->getValue();
7009 MachineMemOperand *MMO = ST->getMemOperand();
7010
7011 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7012 Value);
7013 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7014}
7015
7016// FIXME: Remove this once the ANDI glue bug is fixed:
7017SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7018 assert(Op.getValueType() == MVT::i1 &&
7019 "Custom lowering only for i1 results");
7020
7021 SDLoc DL(Op);
7022 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
7023 Op.getOperand(0));
7024}
7025
7026SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7027 SelectionDAG &DAG) const {
7028
7029 // Implements a vector truncate that fits in a vector register as a shuffle.
7030 // We want to legalize vector truncates down to where the source fits in
7031 // a vector register (and target is therefore smaller than vector register
7032 // size). At that point legalization will try to custom lower the sub-legal
7033 // result and get here - where we can contain the truncate as a single target
7034 // operation.
7035
7036 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7037 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7038 //
7039 // We will implement it for big-endian ordering as this (where x denotes
7040 // undefined):
7041 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7042 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7043 //
7044 // The same operation in little-endian ordering will be:
7045 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7046 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7047
7048 assert(Op.getValueType().isVector() && "Vector type expected.");
7049
7050 SDLoc DL(Op);
7051 SDValue N1 = Op.getOperand(0);
7052 unsigned SrcSize = N1.getValueType().getSizeInBits();
7053 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7054 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7055
7056 EVT TrgVT = Op.getValueType();
7057 unsigned TrgNumElts = TrgVT.getVectorNumElements();
7058 EVT EltVT = TrgVT.getVectorElementType();
7059 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7060 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7061
7062 // First list the elements we want to keep.
7063 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7064 SmallVector<int, 16> ShuffV;
7065 if (Subtarget.isLittleEndian())
7066 for (unsigned i = 0; i < TrgNumElts; ++i)
7067 ShuffV.push_back(i * SizeMult);
7068 else
7069 for (unsigned i = 1; i <= TrgNumElts; ++i)
7070 ShuffV.push_back(i * SizeMult - 1);
7071
7072 // Populate the remaining elements with undefs.
7073 for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7074 // ShuffV.push_back(i + WideNumElts);
7075 ShuffV.push_back(WideNumElts + 1);
7076
7077 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7078 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7079}
7080
7081/// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7082/// possible.
7083SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7084 // Not FP? Not a fsel.
7085 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7086 !Op.getOperand(2).getValueType().isFloatingPoint())
7087 return Op;
7088
7089 // We might be able to do better than this under some circumstances, but in
7090 // general, fsel-based lowering of select is a finite-math-only optimization.
7091 // For more information, see section F.3 of the 2.06 ISA specification.
7092 if (!DAG.getTarget().Options.NoInfsFPMath ||
7093 !DAG.getTarget().Options.NoNaNsFPMath)
7094 return Op;
7095 // TODO: Propagate flags from the select rather than global settings.
7096 SDNodeFlags Flags;
7097 Flags.setNoInfs(true);
7098 Flags.setNoNaNs(true);
7099
7100 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7101
7102 EVT ResVT = Op.getValueType();
7103 EVT CmpVT = Op.getOperand(0).getValueType();
7104 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7105 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
7106 SDLoc dl(Op);
7107
7108 // If the RHS of the comparison is a 0.0, we don't need to do the
7109 // subtraction at all.
7110 SDValue Sel1;
7111 if (isFloatingPointZero(RHS))
7112 switch (CC) {
7113 default: break; // SETUO etc aren't handled by fsel.
7114 case ISD::SETNE:
7115 std::swap(TV, FV);
7116 LLVM_FALLTHROUGH;
7117 case ISD::SETEQ:
7118 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
7119 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7120 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7121 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
7122 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7123 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7124 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7125 case ISD::SETULT:
7126 case ISD::SETLT:
7127 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
7128 LLVM_FALLTHROUGH;
7129 case ISD::SETOGE:
7130 case ISD::SETGE:
7131 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
7132 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7133 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7134 case ISD::SETUGT:
7135 case ISD::SETGT:
7136 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
7137 LLVM_FALLTHROUGH;
7138 case ISD::SETOLE:
7139 case ISD::SETLE:
7140 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
7141 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7142 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7143 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7144 }
7145
7146 SDValue Cmp;
7147 switch (CC) {
7148 default: break; // SETUO etc aren't handled by fsel.
7149 case ISD::SETNE:
7150 std::swap(TV, FV);
7151 LLVM_FALLTHROUGH;
7152 case ISD::SETEQ:
7153 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7154 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
7155 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7156 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7157 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
7158 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7159 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7160 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7161 case ISD::SETULT:
7162 case ISD::SETLT:
7163 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7164 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
7165 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7166 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7167 case ISD::SETOGE:
7168 case ISD::SETGE:
7169 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7170 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
7171 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7172 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7173 case ISD::SETUGT:
7174 case ISD::SETGT:
7175 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7176 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
7177 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7178 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7179 case ISD::SETOLE:
7180 case ISD::SETLE:
7181 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7182 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
7183 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7184 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7185 }
7186 return Op;
7187}
7188
7189void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7190 SelectionDAG &DAG,
7191 const SDLoc &dl) const {
7192 assert(Op.getOperand(0).getValueType().isFloatingPoint());
7193 SDValue Src = Op.getOperand(0);
7194 if (Src.getValueType() == MVT::f32)
7195 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7196
7197 SDValue Tmp;
7198 switch (Op.getSimpleValueType().SimpleTy) {
7199 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7200 case MVT::i32:
7201 Tmp = DAG.getNode(
7202 Op.getOpcode() == ISD::FP_TO_SINT
7203 ? PPCISD::FCTIWZ
7204 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7205 dl, MVT::f64, Src);
7206 break;
7207 case MVT::i64:
7208 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7209 "i64 FP_TO_UINT is supported only with FPCVT");
7210 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7211 PPCISD::FCTIDUZ,
7212 dl, MVT::f64, Src);
7213 break;
7214 }
7215
7216 // Convert the FP value to an int value through memory.
7217 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7218 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7219 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7220 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7221 MachinePointerInfo MPI =
7222 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7223
7224 // Emit a store to the stack slot.
7225 SDValue Chain;
7226 if (i32Stack) {
7227 MachineFunction &MF = DAG.getMachineFunction();
7228 MachineMemOperand *MMO =
7229 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7230 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7231 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7232 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7233 } else
7234 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7235
7236 // Result is a load from the stack slot. If loading 4 bytes, make sure to
7237 // add in a bias on big endian.
7238 if (Op.getValueType() == MVT::i32 && !i32Stack) {
7239 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7240 DAG.getConstant(4, dl, FIPtr.getValueType()));
7241 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7242 }
7243
7244 RLI.Chain = Chain;
7245 RLI.Ptr = FIPtr;
7246 RLI.MPI = MPI;
7247}
7248
7249/// Custom lowers floating point to integer conversions to use
7250/// the direct move instructions available in ISA 2.07 to avoid the
7251/// need for load/store combinations.
7252SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7253 SelectionDAG &DAG,
7254 const SDLoc &dl) const {
7255 assert(Op.getOperand(0).getValueType().isFloatingPoint());
7256 SDValue Src = Op.getOperand(0);
7257
7258 if (Src.getValueType() == MVT::f32)
7259 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7260
7261 SDValue Tmp;
7262 switch (Op.getSimpleValueType().SimpleTy) {
7263 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7264 case MVT::i32:
7265 Tmp = DAG.getNode(
7266 Op.getOpcode() == ISD::FP_TO_SINT
7267 ? PPCISD::FCTIWZ
7268 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7269 dl, MVT::f64, Src);
7270 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7271 break;
7272 case MVT::i64:
7273 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7274 "i64 FP_TO_UINT is supported only with FPCVT");
7275 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7276 PPCISD::FCTIDUZ,
7277 dl, MVT::f64, Src);
7278 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7279 break;
7280 }
7281 return Tmp;
7282}
7283
7284SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7285 const SDLoc &dl) const {
7286
7287 // FP to INT conversions are legal for f128.
7288 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7289 return Op;
7290
7291 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7292 // PPC (the libcall is not available).
7293 if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7294 if (Op.getValueType() == MVT::i32) {
7295 if (Op.getOpcode() == ISD::FP_TO_SINT) {
7296 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7297 MVT::f64, Op.getOperand(0),
7298 DAG.getIntPtrConstant(0, dl));
7299 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7300 MVT::f64, Op.getOperand(0),
7301 DAG.getIntPtrConstant(1, dl));
7302
7303 // Add the two halves of the long double in round-to-zero mode.
7304 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7305
7306 // Now use a smaller FP_TO_SINT.
7307 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7308 }
7309 if (Op.getOpcode() == ISD::FP_TO_UINT) {
7310 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7311 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7312 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7313 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7314 // FIXME: generated code sucks.
7315 // TODO: Are there fast-math-flags to propagate to this FSUB?
7316 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7317 Op.getOperand(0), Tmp);
7318 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7319 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7320 DAG.getConstant(0x80000000, dl, MVT::i32));
7321 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7322 Op.getOperand(0));
7323 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7324 ISD::SETGE);
7325 }
7326 }
7327
7328 return SDValue();
7329 }
7330
7331 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7332 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7333
7334 ReuseLoadInfo RLI;
7335 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7336
7337 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7338 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7339}
7340
7341// We're trying to insert a regular store, S, and then a load, L. If the
7342// incoming value, O, is a load, we might just be able to have our load use the
7343// address used by O. However, we don't know if anything else will store to
7344// that address before we can load from it. To prevent this situation, we need
7345// to insert our load, L, into the chain as a peer of O. To do this, we give L
7346// the same chain operand as O, we create a token factor from the chain results
7347// of O and L, and we replace all uses of O's chain result with that token
7348// factor (see spliceIntoChain below for this last part).
7349bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7350 ReuseLoadInfo &RLI,
7351 SelectionDAG &DAG,
7352 ISD::LoadExtType ET) const {
7353 SDLoc dl(Op);
7354 if (ET == ISD::NON_EXTLOAD &&
7355 (Op.getOpcode() == ISD::FP_TO_UINT ||
7356 Op.getOpcode() == ISD::FP_TO_SINT) &&
7357 isOperationLegalOrCustom(Op.getOpcode(),
7358 Op.getOperand(0).getValueType())) {
7359
7360 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7361 return true;
7362 }
7363
7364 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7365 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7366 LD->isNonTemporal())
7367 return false;
7368 if (LD->getMemoryVT() != MemVT)
7369 return false;
7370
7371 RLI.Ptr = LD->getBasePtr();
7372 if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7373 assert(LD->getAddressingMode() == ISD::PRE_INC &&
7374 "Non-pre-inc AM on PPC?");
7375 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7376 LD->getOffset());
7377 }
7378
7379 RLI.Chain = LD->getChain();
7380 RLI.MPI = LD->getPointerInfo();
7381 RLI.IsDereferenceable = LD->isDereferenceable();
7382 RLI.IsInvariant = LD->isInvariant();
7383 RLI.Alignment = LD->getAlignment();
7384 RLI.AAInfo = LD->getAAInfo();
7385 RLI.Ranges = LD->getRanges();
7386
7387 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7388 return true;
7389}
7390
7391// Given the head of the old chain, ResChain, insert a token factor containing
7392// it and NewResChain, and make users of ResChain now be users of that token
7393// factor.
7394// TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7395void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7396 SDValue NewResChain,
7397 SelectionDAG &DAG) const {
7398 if (!ResChain)
7399 return;
7400
7401 SDLoc dl(NewResChain);
7402
7403 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7404 NewResChain, DAG.getUNDEF(MVT::Other));
7405 assert(TF.getNode() != NewResChain.getNode() &&
7406 "A new TF really is required here");
7407
7408 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7409 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7410}
7411
7412/// Analyze profitability of direct move
7413/// prefer float load to int load plus direct move
7414/// when there is no integer use of int load
7415bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7416 SDNode *Origin = Op.getOperand(0).getNode();
7417 if (Origin->getOpcode() != ISD::LOAD)
7418 return true;
7419
7420 // If there is no LXSIBZX/LXSIHZX, like Power8,
7421 // prefer direct move if the memory size is 1 or 2 bytes.
7422 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7423 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7424 return true;
7425
7426 for (SDNode::use_iterator UI = Origin->use_begin(),
7427 UE = Origin->use_end();
7428 UI != UE; ++UI) {
7429
7430 // Only look at the users of the loaded value.
7431 if (UI.getUse().get().getResNo() != 0)
7432 continue;
7433
7434 if (UI->getOpcode() != ISD::SINT_TO_FP &&
7435 UI->getOpcode() != ISD::UINT_TO_FP)
7436 return true;
7437 }
7438
7439 return false;
7440}
7441
7442/// Custom lowers integer to floating point conversions to use
7443/// the direct move instructions available in ISA 2.07 to avoid the
7444/// need for load/store combinations.
7445SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7446 SelectionDAG &DAG,
7447 const SDLoc &dl) const {
7448 assert((Op.getValueType() == MVT::f32 ||
7449 Op.getValueType() == MVT::f64) &&
7450 "Invalid floating point type as target of conversion");
7451 assert(Subtarget.hasFPCVT() &&
7452 "Int to FP conversions with direct moves require FPCVT");
7453 SDValue FP;
7454 SDValue Src = Op.getOperand(0);
7455 bool SinglePrec = Op.getValueType() == MVT::f32;
7456 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7457 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7458 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7459 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7460
7461 if (WordInt) {
7462 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7463 dl, MVT::f64, Src);
7464 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7465 }
7466 else {
7467 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7468 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7469 }
7470
7471 return FP;
7472}
7473
7474static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7475
7476 EVT VecVT = Vec.getValueType();
7477 assert(VecVT.isVector() && "Expected a vector type.");
7478 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7479
7480 EVT EltVT = VecVT.getVectorElementType();
7481 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7482 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7483
7484 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7485 SmallVector<SDValue, 16> Ops(NumConcat);
7486 Ops[0] = Vec;
7487 SDValue UndefVec = DAG.getUNDEF(VecVT);
7488 for (unsigned i = 1; i < NumConcat; ++i)
7489 Ops[i] = UndefVec;
7490
7491 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7492}
7493
7494SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7495 const SDLoc &dl) const {
7496
7497 unsigned Opc = Op.getOpcode();
7498 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7499 "Unexpected conversion type");
7500 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7501 "Supports conversions to v2f64/v4f32 only.");
7502
7503 bool SignedConv = Opc == ISD::SINT_TO_FP;
7504 bool FourEltRes = Op.getValueType() == MVT::v4f32;
7505
7506 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7507 EVT WideVT = Wide.getValueType();
7508 unsigned WideNumElts = WideVT.getVectorNumElements();
7509 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7510
7511 SmallVector<int, 16> ShuffV;
7512 for (unsigned i = 0; i < WideNumElts; ++i)
7513 ShuffV.push_back(i + WideNumElts);
7514
7515 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7516 int SaveElts = FourEltRes ? 4 : 2;
7517 if (Subtarget.isLittleEndian())
7518 for (int i = 0; i < SaveElts; i++)
7519 ShuffV[i * Stride] = i;
7520 else
7521 for (int i = 1; i <= SaveElts; i++)
7522 ShuffV[i * Stride - 1] = i - 1;
7523
7524 SDValue ShuffleSrc2 =
7525 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7526 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7527 unsigned ExtendOp =
7528 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7529
7530 SDValue Extend;
7531 if (!Subtarget.hasP9Altivec() && SignedConv) {
7532 Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7533 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7534 DAG.getValueType(Op.getOperand(0).getValueType()));
7535 } else
7536 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7537
7538 return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7539}
7540
7541SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7542 SelectionDAG &DAG) const {
7543 SDLoc dl(Op);
7544
7545 EVT InVT = Op.getOperand(0).getValueType();
7546 EVT OutVT = Op.getValueType();
7547 if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7548 isOperationCustom(Op.getOpcode(), InVT))
7549 return LowerINT_TO_FPVector(Op, DAG, dl);
7550
7551 // Conversions to f128 are legal.
7552 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7553 return Op;
7554
7555 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7556 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7557 return SDValue();
7558
7559 SDValue Value = Op.getOperand(0);
7560 // The values are now known to be -1 (false) or 1 (true). To convert this
7561 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7562 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7563 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7564
7565 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7566
7567 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7568
7569 if (Op.getValueType() != MVT::v4f64)
7570 Value = DAG.getNode(ISD::FP_ROUND, dl,
7571 Op.getValueType(), Value,
7572 DAG.getIntPtrConstant(1, dl));
7573 return Value;
7574 }
7575
7576 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7577 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7578 return SDValue();
7579
7580 if (Op.getOperand(0).getValueType() == MVT::i1)
7581 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7582 DAG.getConstantFP(1.0, dl, Op.getValueType()),
7583 DAG.getConstantFP(0.0, dl, Op.getValueType()));
7584
7585 // If we have direct moves, we can do all the conversion, skip the store/load
7586 // however, without FPCVT we can't do most conversions.
7587 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7588 Subtarget.isPPC64() && Subtarget.hasFPCVT())
7589 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7590
7591 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7592 "UINT_TO_FP is supported only with FPCVT");
7593
7594 // If we have FCFIDS, then use it when converting to single-precision.
7595 // Otherwise, convert to double-precision and then round.
7596 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7597 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7598 : PPCISD::FCFIDS)
7599 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7600 : PPCISD::FCFID);
7601 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7602 ? MVT::f32
7603 : MVT::f64;
7604
7605 if (Op.getOperand(0).getValueType() == MVT::i64) {
7606 SDValue SINT = Op.getOperand(0);
7607 // When converting to single-precision, we actually need to convert
7608 // to double-precision first and then round to single-precision.
7609 // To avoid double-rounding effects during that operation, we have
7610 // to prepare the input operand. Bits that might be truncated when
7611 // converting to double-precision are replaced by a bit that won't
7612 // be lost at this stage, but is below the single-precision rounding
7613 // position.
7614 //
7615 // However, if -enable-unsafe-fp-math is in effect, accept double
7616 // rounding to avoid the extra overhead.
7617 if (Op.getValueType() == MVT::f32 &&
7618 !Subtarget.hasFPCVT() &&
7619 !DAG.getTarget().Options.UnsafeFPMath) {
7620
7621 // Twiddle input to make sure the low 11 bits are zero. (If this
7622 // is the case, we are guaranteed the value will fit into the 53 bit
7623 // mantissa of an IEEE double-precision value without rounding.)
7624 // If any of those low 11 bits were not zero originally, make sure
7625 // bit 12 (value 2048) is set instead, so that the final rounding
7626 // to single-precision gets the correct result.
7627 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7628 SINT, DAG.getConstant(2047, dl, MVT::i64));
7629 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7630 Round, DAG.getConstant(2047, dl, MVT::i64));
7631 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7632 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7633 Round, DAG.getConstant(-2048, dl, MVT::i64));
7634
7635 // However, we cannot use that value unconditionally: if the magnitude
7636 // of the input value is small, the bit-twiddling we did above might
7637 // end up visibly changing the output. Fortunately, in that case, we
7638 // don't need to twiddle bits since the original input will convert
7639 // exactly to double-precision floating-point already. Therefore,
7640 // construct a conditional to use the original value if the top 11
7641 // bits are all sign-bit copies, and use the rounded value computed
7642 // above otherwise.
7643 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7644 SINT, DAG.getConstant(53, dl, MVT::i32));
7645 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7646 Cond, DAG.getConstant(1, dl, MVT::i64));
7647 Cond = DAG.getSetCC(dl, MVT::i32,
7648 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7649
7650 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7651 }
7652
7653 ReuseLoadInfo RLI;
7654 SDValue Bits;
7655
7656 MachineFunction &MF = DAG.getMachineFunction();
7657 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7658 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7659 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7660 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7661 } else if (Subtarget.hasLFIWAX() &&
7662 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7663 MachineMemOperand *MMO =
7664 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7665 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7666 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7667 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7668 DAG.getVTList(MVT::f64, MVT::Other),
7669 Ops, MVT::i32, MMO);
7670 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7671 } else if (Subtarget.hasFPCVT() &&
7672 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7673 MachineMemOperand *MMO =
7674 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7675 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7676 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7677 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7678 DAG.getVTList(MVT::f64, MVT::Other),
7679 Ops, MVT::i32, MMO);
7680 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7681 } else if (((Subtarget.hasLFIWAX() &&
7682 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7683 (Subtarget.hasFPCVT() &&
7684 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7685 SINT.getOperand(0).getValueType() == MVT::i32) {
7686 MachineFrameInfo &MFI = MF.getFrameInfo();
7687 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7688
7689 int FrameIdx = MFI.CreateStackObject(4, 4, false);
7690 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7691
7692 SDValue Store =
7693 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7694 MachinePointerInfo::getFixedStack(
7695 DAG.getMachineFunction(), FrameIdx));
7696
7697 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7698 "Expected an i32 store");
7699
7700 RLI.Ptr = FIdx;
7701 RLI.Chain = Store;
7702 RLI.MPI =
7703 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7704 RLI.Alignment = 4;
7705
7706 MachineMemOperand *MMO =
7707 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7708 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7709 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7710 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7711 PPCISD::LFIWZX : PPCISD::LFIWAX,
7712 dl, DAG.getVTList(MVT::f64, MVT::Other),
7713 Ops, MVT::i32, MMO);
7714 } else
7715 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7716
7717 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7718
7719 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7720 FP = DAG.getNode(ISD::FP_ROUND, dl,
7721 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7722 return FP;
7723 }
7724
7725 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7726 "Unhandled INT_TO_FP type in custom expander!");
7727 // Since we only generate this in 64-bit mode, we can take advantage of
7728 // 64-bit registers. In particular, sign extend the input value into the
7729 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7730 // then lfd it and fcfid it.
7731 MachineFunction &MF = DAG.getMachineFunction();
7732 MachineFrameInfo &MFI = MF.getFrameInfo();
7733 EVT PtrVT = getPointerTy(MF.getDataLayout());
7734
7735 SDValue Ld;
7736 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7737 ReuseLoadInfo RLI;
7738 bool ReusingLoad;
7739 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7740 DAG))) {
7741 int FrameIdx = MFI.CreateStackObject(4, 4, false);
7742 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7743
7744 SDValue Store =
7745 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7746 MachinePointerInfo::getFixedStack(
7747 DAG.getMachineFunction(), FrameIdx));
7748
7749 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7750 "Expected an i32 store");
7751
7752 RLI.Ptr = FIdx;
7753 RLI.Chain = Store;
7754 RLI.MPI =
7755 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7756 RLI.Alignment = 4;
7757 }
7758
7759 MachineMemOperand *MMO =
7760 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7761 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7762 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7763 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7764 PPCISD::LFIWZX : PPCISD::LFIWAX,
7765 dl, DAG.getVTList(MVT::f64, MVT::Other),
7766 Ops, MVT::i32, MMO);
7767 if (ReusingLoad)
7768 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7769 } else {
7770 assert(Subtarget.isPPC64() &&
7771 "i32->FP without LFIWAX supported only on PPC64");
7772
7773 int FrameIdx = MFI.CreateStackObject(8, 8, false);
7774 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7775
7776 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7777 Op.getOperand(0));
7778
7779 // STD the extended value into the stack slot.
7780 SDValue Store = DAG.getStore(
7781 DAG.getEntryNode(), dl, Ext64, FIdx,
7782 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7783
7784 // Load the value as a double.
7785 Ld = DAG.getLoad(
7786 MVT::f64, dl, Store, FIdx,
7787 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7788 }
7789
7790 // FCFID it and return it.
7791 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7792 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7793 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7794 DAG.getIntPtrConstant(0, dl));
7795 return FP;
7796}
7797
7798SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7799 SelectionDAG &DAG) const {
7800 SDLoc dl(Op);
7801 /*
7802 The rounding mode is in bits 30:31 of FPSR, and has the following
7803 settings:
7804 00 Round to nearest
7805 01 Round to 0
7806 10 Round to +inf
7807 11 Round to -inf
7808
7809 FLT_ROUNDS, on the other hand, expects the following:
7810 -1 Undefined
7811 0 Round to 0
7812 1 Round to nearest
7813 2 Round to +inf
7814 3 Round to -inf
7815
7816 To perform the conversion, we do:
7817 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7818 */
7819
7820 MachineFunction &MF = DAG.getMachineFunction();
7821 EVT VT = Op.getValueType();
7822 EVT PtrVT = getPointerTy(MF.getDataLayout());
7823
7824 // Save FP Control Word to register
7825 EVT NodeTys[] = {
7826 MVT::f64, // return register
7827 MVT::Glue // unused in this context
7828 };
7829 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7830
7831 // Save FP register to stack slot
7832 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7833 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7834 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7835 MachinePointerInfo());
7836
7837 // Load FP Control Word from low 32 bits of stack slot.
7838 SDValue Four = DAG.getConstant(4, dl, PtrVT);
7839 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7840 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7841
7842 // Transform as necessary
7843 SDValue CWD1 =
7844 DAG.getNode(ISD::AND, dl, MVT::i32,
7845 CWD, DAG.getConstant(3, dl, MVT::i32));
7846 SDValue CWD2 =
7847 DAG.getNode(ISD::SRL, dl, MVT::i32,
7848 DAG.getNode(ISD::AND, dl, MVT::i32,
7849 DAG.getNode(ISD::XOR, dl, MVT::i32,
7850 CWD, DAG.getConstant(3, dl, MVT::i32)),
7851 DAG.getConstant(3, dl, MVT::i32)),
7852 DAG.getConstant(1, dl, MVT::i32));
7853
7854 SDValue RetVal =
7855 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7856
7857 return DAG.getNode((VT.getSizeInBits() < 16 ?
7858 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7859}
7860
7861SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7862 EVT VT = Op.getValueType();
7863 unsigned BitWidth = VT.getSizeInBits();
7864 SDLoc dl(Op);
7865 assert(Op.getNumOperands() == 3 &&
7866 VT == Op.getOperand(1).getValueType() &&
7867 "Unexpected SHL!");
7868
7869 // Expand into a bunch of logical ops. Note that these ops
7870 // depend on the PPC behavior for oversized shift amounts.
7871 SDValue Lo = Op.getOperand(0);
7872 SDValue Hi = Op.getOperand(1);
7873 SDValue Amt = Op.getOperand(2);
7874 EVT AmtVT = Amt.getValueType();
7875
7876 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7877 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7878 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7879 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7880 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7881 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7882 DAG.getConstant(-BitWidth, dl, AmtVT));
7883 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7884 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7885 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7886 SDValue OutOps[] = { OutLo, OutHi };
7887 return DAG.getMergeValues(OutOps, dl);
7888}
7889
7890SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7891 EVT VT = Op.getValueType();
7892 SDLoc dl(Op);
7893 unsigned BitWidth = VT.getSizeInBits();
7894 assert(Op.getNumOperands() == 3 &&
7895 VT == Op.getOperand(1).getValueType() &&
7896 "Unexpected SRL!");
7897
7898 // Expand into a bunch of logical ops. Note that these ops
7899 // depend on the PPC behavior for oversized shift amounts.
7900 SDValue Lo = Op.getOperand(0);
7901 SDValue Hi = Op.getOperand(1);
7902 SDValue Amt = Op.getOperand(2);
7903 EVT AmtVT = Amt.getValueType();
7904
7905 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7906 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7907 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7908 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7909 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7910 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7911 DAG.getConstant(-BitWidth, dl, AmtVT));
7912 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7913 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7914 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7915 SDValue OutOps[] = { OutLo, OutHi };
7916 return DAG.getMergeValues(OutOps, dl);
7917}
7918
7919SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7920 SDLoc dl(Op);
7921 EVT VT = Op.getValueType();
7922 unsigned BitWidth = VT.getSizeInBits();
7923 assert(Op.getNumOperands() == 3 &&
7924 VT == Op.getOperand(1).getValueType() &&
7925 "Unexpected SRA!");
7926
7927 // Expand into a bunch of logical ops, followed by a select_cc.
7928 SDValue Lo = Op.getOperand(0);
7929 SDValue Hi = Op.getOperand(1);
7930 SDValue Amt = Op.getOperand(2);
7931 EVT AmtVT = Amt.getValueType();
7932
7933 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7934 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7935 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7936 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7937 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7938 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7939 DAG.getConstant(-BitWidth, dl, AmtVT));
7940 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7941 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7942 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7943 Tmp4, Tmp6, ISD::SETLE);
7944 SDValue OutOps[] = { OutLo, OutHi };
7945 return DAG.getMergeValues(OutOps, dl);
7946}
7947
7948//===----------------------------------------------------------------------===//
7949// Vector related lowering.
7950//
7951
7952/// BuildSplatI - Build a canonical splati of Val with an element size of
7953/// SplatSize. Cast the result to VT.
7954static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7955 SelectionDAG &DAG, const SDLoc &dl) {
7956 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7957
7958 static const MVT VTys[] = { // canonical VT to use for each size.
7959 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7960 };
7961
7962 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7963
7964 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7965 if (Val == -1)
7966 SplatSize = 1;
7967
7968 EVT CanonicalVT = VTys[SplatSize-1];
7969
7970 // Build a canonical splat for this value.
7971 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7972}
7973
7974/// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7975/// specified intrinsic ID.
7976static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7977 const SDLoc &dl, EVT DestVT = MVT::Other) {
7978 if (DestVT == MVT::Other) DestVT = Op.getValueType();
7979 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7980 DAG.getConstant(IID, dl, MVT::i32), Op);
7981}
7982
7983/// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7984/// specified intrinsic ID.
7985static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7986 SelectionDAG &DAG, const SDLoc &dl,
7987 EVT DestVT = MVT::Other) {
7988 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7989 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7990 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7991}
7992
7993/// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7994/// specified intrinsic ID.
7995static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7996 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7997 EVT DestVT = MVT::Other) {
7998 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7999 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8000 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8001}
8002
8003/// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8004/// amount. The result has the specified value type.
8005static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8006 SelectionDAG &DAG, const SDLoc &dl) {
8007 // Force LHS/RHS to be the right type.
8008 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8009 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8010
8011 int Ops[16];
8012 for (unsigned i = 0; i != 16; ++i)
8013 Ops[i] = i + Amt;
8014 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8015 return DAG.getNode(ISD::BITCAST, dl, VT, T);
8016}
8017
8018/// Do we have an efficient pattern in a .td file for this node?
8019///
8020/// \param V - pointer to the BuildVectorSDNode being matched
8021/// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8022///
8023/// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8024/// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8025/// the opposite is true (expansion is beneficial) are:
8026/// - The node builds a vector out of integers that are not 32 or 64-bits
8027/// - The node builds a vector out of constants
8028/// - The node is a "load-and-splat"
8029/// In all other cases, we will choose to keep the BUILD_VECTOR.
8030static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8031 bool HasDirectMove,
8032 bool HasP8Vector) {
8033 EVT VecVT = V->getValueType(0);
8034 bool RightType = VecVT == MVT::v2f64 ||
8035 (HasP8Vector && VecVT == MVT::v4f32) ||
8036 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8037 if (!RightType)
8038 return false;
8039
8040 bool IsSplat = true;
8041 bool IsLoad = false;
8042 SDValue Op0 = V->getOperand(0);
8043
8044 // This function is called in a block that confirms the node is not a constant
8045 // splat. So a constant BUILD_VECTOR here means the vector is built out of
8046 // different constants.
8047 if (V->isConstant())
8048 return false;
8049 for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8050 if (V->getOperand(i).isUndef())
8051 return false;
8052 // We want to expand nodes that represent load-and-splat even if the
8053 // loaded value is a floating point truncation or conversion to int.
8054 if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8055 (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8056 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8057 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8058 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8059 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8060 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8061 IsLoad = true;
8062 // If the operands are different or the input is not a load and has more
8063 // uses than just this BV node, then it isn't a splat.
8064 if (V->getOperand(i) != Op0 ||
8065 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8066 IsSplat = false;
8067 }
8068 return !(IsSplat && IsLoad);
8069}
8070
8071// Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8072SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8073
8074 SDLoc dl(Op);
8075 SDValue Op0 = Op->getOperand(0);
8076
8077 if (!EnableQuadPrecision ||
8078 (Op.getValueType() != MVT::f128 ) ||
8079 (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8080 (Op0.getOperand(0).getValueType() != MVT::i64) ||
8081 (Op0.getOperand(1).getValueType() != MVT::i64))
8082 return SDValue();
8083
8084 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8085 Op0.getOperand(1));
8086}
8087
8088// If this is a case we can't handle, return null and let the default
8089// expansion code take care of it. If we CAN select this case, and if it
8090// selects to a single instruction, return Op. Otherwise, if we can codegen
8091// this case more efficiently than a constant pool load, lower it to the
8092// sequence of ops that should be used.
8093SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8094 SelectionDAG &DAG) const {
8095 SDLoc dl(Op);
8096 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8097 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8098
8099 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8100 // We first build an i32 vector, load it into a QPX register,
8101 // then convert it to a floating-point vector and compare it
8102 // to a zero vector to get the boolean result.
8103 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8104 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8105 MachinePointerInfo PtrInfo =
8106 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8107 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8108 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8109
8110 assert(BVN->getNumOperands() == 4 &&
8111 "BUILD_VECTOR for v4i1 does not have 4 operands");
8112
8113 bool IsConst = true;
8114 for (unsigned i = 0; i < 4; ++i) {
8115 if (BVN->getOperand(i).isUndef()) continue;
8116 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8117 IsConst = false;
8118 break;
8119 }
8120 }
8121
8122 if (IsConst) {
8123 Constant *One =
8124 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8125 Constant *NegOne =
8126 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8127
8128 Constant *CV[4];
8129 for (unsigned i = 0; i < 4; ++i) {
8130 if (BVN->getOperand(i).isUndef())
8131 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8132 else if (isNullConstant(BVN->getOperand(i)))
8133 CV[i] = NegOne;
8134 else
8135 CV[i] = One;
8136 }
8137
8138 Constant *CP = ConstantVector::get(CV);
8139 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8140 16 /* alignment */);
8141
8142 SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8143 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8144 return DAG.getMemIntrinsicNode(
8145 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8146 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8147 }
8148
8149 SmallVector<SDValue, 4> Stores;
8150 for (unsigned i = 0; i < 4; ++i) {
8151 if (BVN->getOperand(i).isUndef()) continue;
8152
8153 unsigned Offset = 4*i;
8154 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8155 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8156
8157 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8158 if (StoreSize > 4) {
8159 Stores.push_back(
8160 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8161 PtrInfo.getWithOffset(Offset), MVT::i32));
8162 } else {
8163 SDValue StoreValue = BVN->getOperand(i);
8164 if (StoreSize < 4)
8165 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8166
8167 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8168 PtrInfo.getWithOffset(Offset)));
8169 }
8170 }
8171
8172 SDValue StoreChain;
8173 if (!Stores.empty())
8174 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8175 else
8176 StoreChain = DAG.getEntryNode();
8177
8178 // Now load from v4i32 into the QPX register; this will extend it to
8179 // v4i64 but not yet convert it to a floating point. Nevertheless, this
8180 // is typed as v4f64 because the QPX register integer states are not
8181 // explicitly represented.
8182
8183 SDValue Ops[] = {StoreChain,
8184 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8185 FIdx};
8186 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8187
8188 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8189 dl, VTs, Ops, MVT::v4i32, PtrInfo);
8190 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8191 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8192 LoadedVect);
8193
8194 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8195
8196 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8197 }
8198
8199 // All other QPX vectors are handled by generic code.
8200 if (Subtarget.hasQPX())
8201 return SDValue();
8202
8203 // Check if this is a splat of a constant value.
8204 APInt APSplatBits, APSplatUndef;
8205 unsigned SplatBitSize;
8206 bool HasAnyUndefs;
8207 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8208 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8209 SplatBitSize > 32) {
8210 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8211 // lowered to VSX instructions under certain conditions.
8212 // Without VSX, there is no pattern more efficient than expanding the node.
8213 if (Subtarget.hasVSX() &&
8214 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8215 Subtarget.hasP8Vector()))
8216 return Op;
8217 return SDValue();
8218 }
8219
8220 unsigned SplatBits = APSplatBits.getZExtValue();
8221 unsigned SplatUndef = APSplatUndef.getZExtValue();
8222 unsigned SplatSize = SplatBitSize / 8;
8223
8224 // First, handle single instruction cases.
8225
8226 // All zeros?
8227 if (SplatBits == 0) {
8228 // Canonicalize all zero vectors to be v4i32.
8229 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8230 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8231 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8232 }
8233 return Op;
8234 }
8235
8236 // We have XXSPLTIB for constant splats one byte wide
8237 if (Subtarget.hasP9Vector() && SplatSize == 1) {
8238 // This is a splat of 1-byte elements with some elements potentially undef.
8239 // Rather than trying to match undef in the SDAG patterns, ensure that all
8240 // elements are the same constant.
8241 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
8242 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
8243 dl, MVT::i32));
8244 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
8245 if (Op.getValueType() != MVT::v16i8)
8246 return DAG.getBitcast(Op.getValueType(), NewBV);
8247 return NewBV;
8248 }
8249
8250 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
8251 // detect that constant splats like v8i16: 0xABAB are really just splats
8252 // of a 1-byte constant. In this case, we need to convert the node to a
8253 // splat of v16i8 and a bitcast.
8254 if (Op.getValueType() != MVT::v16i8)
8255 return DAG.getBitcast(Op.getValueType(),
8256 DAG.getConstant(SplatBits, dl, MVT::v16i8));
8257
8258 return Op;
8259 }
8260
8261 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8262 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8263 (32-SplatBitSize));
8264 if (SextVal >= -16 && SextVal <= 15)
8265 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8266
8267 // Two instruction sequences.
8268
8269 // If this value is in the range [-32,30] and is even, use:
8270 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8271 // If this value is in the range [17,31] and is odd, use:
8272 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8273 // If this value is in the range [-31,-17] and is odd, use:
8274 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8275 // Note the last two are three-instruction sequences.
8276 if (SextVal >= -32 && SextVal <= 31) {
8277 // To avoid having these optimizations undone by constant folding,
8278 // we convert to a pseudo that will be expanded later into one of
8279 // the above forms.
8280 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8281 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8282 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8283 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8284 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8285 if (VT == Op.getValueType())
8286 return RetVal;
8287 else
8288 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8289 }
8290
8291 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
8292 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
8293 // for fneg/fabs.
8294 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8295 // Make -1 and vspltisw -1:
8296 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8297
8298 // Make the VSLW intrinsic, computing 0x8000_0000.
8299 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8300 OnesV, DAG, dl);
8301
8302 // xor by OnesV to invert it.
8303 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8304 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8305 }
8306
8307 // Check to see if this is a wide variety of vsplti*, binop self cases.
8308 static const signed char SplatCsts[] = {
8309 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8310 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8311 };
8312
8313 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8314 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8315 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
8316 int i = SplatCsts[idx];
8317
8318 // Figure out what shift amount will be used by altivec if shifted by i in
8319 // this splat size.
8320 unsigned TypeShiftAmt = i & (SplatBitSize-1);
8321
8322 // vsplti + shl self.
8323 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8324 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8325 static const unsigned IIDs[] = { // Intrinsic to use for each size.
8326 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8327 Intrinsic::ppc_altivec_vslw
8328 };
8329 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8330 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8331 }
8332
8333 // vsplti + srl self.
8334 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8335 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8336 static const unsigned IIDs[] = { // Intrinsic to use for each size.
8337 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8338 Intrinsic::ppc_altivec_vsrw
8339 };
8340 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8341 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8342 }
8343
8344 // vsplti + sra self.
8345 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8346 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8347 static const unsigned IIDs[] = { // Intrinsic to use for each size.
8348 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8349 Intrinsic::ppc_altivec_vsraw
8350 };
8351 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8352 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8353 }
8354
8355 // vsplti + rol self.
8356 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8357 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8358 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8359 static const unsigned IIDs[] = { // Intrinsic to use for each size.
8360 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8361 Intrinsic::ppc_altivec_vrlw
8362 };
8363 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8364 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8365 }
8366
8367 // t = vsplti c, result = vsldoi t, t, 1
8368 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8369 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8370 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8371 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8372 }
8373 // t = vsplti c, result = vsldoi t, t, 2
8374 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8375 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8376 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8377 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8378 }
8379 // t = vsplti c, result = vsldoi t, t, 3
8380 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8381 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8382 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8383 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8384 }
8385 }
8386
8387 return SDValue();
8388}
8389
8390/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8391/// the specified operations to build the shuffle.
8392static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8393 SDValue RHS, SelectionDAG &DAG,
8394 const SDLoc &dl) {
8395 unsigned OpNum = (PFEntry >> 26) & 0x0F;
8396 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8397 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
8398
8399 enum {
8400 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8401 OP_VMRGHW,
8402 OP_VMRGLW,
8403 OP_VSPLTISW0,
8404 OP_VSPLTISW1,
8405 OP_VSPLTISW2,
8406 OP_VSPLTISW3,
8407 OP_VSLDOI4,
8408 OP_VSLDOI8,
8409 OP_VSLDOI12
8410 };
8411
8412 if (OpNum == OP_COPY) {
8413 if (LHSID == (1*9+2)*9+3) return LHS;
8414 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8415 return RHS;
8416 }
8417
8418 SDValue OpLHS, OpRHS;
8419 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8420 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8421
8422 int ShufIdxs[16];
8423 switch (OpNum) {
8424 default: llvm_unreachable("Unknown i32 permute!");
8425 case OP_VMRGHW:
8426 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
8427 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8428 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
8429 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8430 break;
8431 case OP_VMRGLW:
8432 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8433 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8434 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8435 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8436 break;
8437 case OP_VSPLTISW0:
8438 for (unsigned i = 0; i != 16; ++i)
8439 ShufIdxs[i] = (i&3)+0;
8440 break;
8441 case OP_VSPLTISW1:
8442 for (unsigned i = 0; i != 16; ++i)
8443 ShufIdxs[i] = (i&3)+4;
8444 break;
8445 case OP_VSPLTISW2:
8446 for (unsigned i = 0; i != 16; ++i)
8447 ShufIdxs[i] = (i&3)+8;
8448 break;
8449 case OP_VSPLTISW3:
8450 for (unsigned i = 0; i != 16; ++i)
8451 ShufIdxs[i] = (i&3)+12;
8452 break;
8453 case OP_VSLDOI4:
8454 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8455 case OP_VSLDOI8:
8456 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8457 case OP_VSLDOI12:
8458 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8459 }
8460 EVT VT = OpLHS.getValueType();
8461 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8462 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8463 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8464 return DAG.getNode(ISD::BITCAST, dl, VT, T);
8465}
8466
8467/// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8468/// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8469/// SDValue.
8470SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8471 SelectionDAG &DAG) const {
8472 const unsigned BytesInVector = 16;
8473 bool IsLE = Subtarget.isLittleEndian();
8474 SDLoc dl(N);
8475 SDValue V1 = N->getOperand(0);
8476 SDValue V2 = N->getOperand(1);
8477 unsigned ShiftElts = 0, InsertAtByte = 0;
8478 bool Swap = false;
8479
8480 // Shifts required to get the byte we want at element 7.
8481 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1,
8482 0, 15, 14, 13, 12, 11, 10, 9};
8483 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8484 1, 2, 3, 4, 5, 6, 7, 8};
8485
8486 ArrayRef<int> Mask = N->getMask();
8487 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8488
8489 // For each mask element, find out if we're just inserting something
8490 // from V2 into V1 or vice versa.
8491 // Possible permutations inserting an element from V2 into V1:
8492 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8493 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8494 // ...
8495 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8496 // Inserting from V1 into V2 will be similar, except mask range will be
8497 // [16,31].
8498
8499 bool FoundCandidate = false;
8500 // If both vector operands for the shuffle are the same vector, the mask
8501 // will contain only elements from the first one and the second one will be
8502 // undef.
8503 unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8504 // Go through the mask of half-words to find an element that's being moved
8505 // from one vector to the other.
8506 for (unsigned i = 0; i < BytesInVector; ++i) {
8507 unsigned CurrentElement = Mask[i];
8508 // If 2nd operand is undefined, we should only look for element 7 in the
8509 // Mask.
8510 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8511 continue;
8512
8513 bool OtherElementsInOrder = true;
8514 // Examine the other elements in the Mask to see if they're in original
8515 // order.
8516 for (unsigned j = 0; j < BytesInVector; ++j) {
8517 if (j == i)
8518 continue;
8519 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8520 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined,
8521 // in which we always assume we're always picking from the 1st operand.
8522 int MaskOffset =
8523 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8524 if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8525 OtherElementsInOrder = false;
8526 break;
8527 }
8528 }
8529 // If other elements are in original order, we record the number of shifts
8530 // we need to get the element we want into element 7. Also record which byte
8531 // in the vector we should insert into.
8532 if (OtherElementsInOrder) {
8533 // If 2nd operand is undefined, we assume no shifts and no swapping.
8534 if (V2.isUndef()) {
8535 ShiftElts = 0;
8536 Swap = false;
8537 } else {
8538 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8539 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8540 : BigEndianShifts[CurrentElement & 0xF];
8541 Swap = CurrentElement < BytesInVector;
8542 }
8543 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8544 FoundCandidate = true;
8545 break;
8546 }
8547 }
8548
8549 if (!FoundCandidate)
8550 return SDValue();
8551
8552 // Candidate found, construct the proper SDAG sequence with VINSERTB,
8553 // optionally with VECSHL if shift is required.
8554 if (Swap)
8555 std::swap(V1, V2);
8556 if (V2.isUndef())
8557 V2 = V1;
8558 if (ShiftElts) {
8559 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8560 DAG.getConstant(ShiftElts, dl, MVT::i32));
8561 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8562 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8563 }
8564 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8565 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8566}
8567
8568/// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8569/// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8570/// SDValue.
8571SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8572 SelectionDAG &DAG) const {
8573 const unsigned NumHalfWords = 8;
8574 const unsigned BytesInVector = NumHalfWords * 2;
8575 // Check that the shuffle is on half-words.
8576 if (!isNByteElemShuffleMask(N, 2, 1))
8577 return SDValue();
8578
8579 bool IsLE = Subtarget.isLittleEndian();
8580 SDLoc dl(N);
8581 SDValue V1 = N->getOperand(0);
8582 SDValue V2 = N->getOperand(1);
8583 unsigned ShiftElts = 0, InsertAtByte = 0;
8584 bool Swap = false;
8585
8586 // Shifts required to get the half-word we want at element 3.
8587 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8588 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8589
8590 uint32_t Mask = 0;
8591 uint32_t OriginalOrderLow = 0x1234567;
8592 uint32_t OriginalOrderHigh = 0x89ABCDEF;
8593 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a
8594 // 32-bit space, only need 4-bit nibbles per element.
8595 for (unsigned i = 0; i < NumHalfWords; ++i) {
8596 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8597 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8598 }
8599
8600 // For each mask element, find out if we're just inserting something
8601 // from V2 into V1 or vice versa. Possible permutations inserting an element
8602 // from V2 into V1:
8603 // X, 1, 2, 3, 4, 5, 6, 7
8604 // 0, X, 2, 3, 4, 5, 6, 7
8605 // 0, 1, X, 3, 4, 5, 6, 7
8606 // 0, 1, 2, X, 4, 5, 6, 7
8607 // 0, 1, 2, 3, X, 5, 6, 7
8608 // 0, 1, 2, 3, 4, X, 6, 7
8609 // 0, 1, 2, 3, 4, 5, X, 7
8610 // 0, 1, 2, 3, 4, 5, 6, X
8611 // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8612
8613 bool FoundCandidate = false;
8614 // Go through the mask of half-words to find an element that's being moved
8615 // from one vector to the other.
8616 for (unsigned i = 0; i < NumHalfWords; ++i) {
8617 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8618 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8619 uint32_t MaskOtherElts = ~(0xF << MaskShift);
8620 uint32_t TargetOrder = 0x0;
8621
8622 // If both vector operands for the shuffle are the same vector, the mask
8623 // will contain only elements from the first one and the second one will be
8624 // undef.
8625 if (V2.isUndef()) {
8626 ShiftElts = 0;
8627 unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8628 TargetOrder = OriginalOrderLow;
8629 Swap = false;
8630 // Skip if not the correct element or mask of other elements don't equal
8631 // to our expected order.
8632 if (MaskOneElt == VINSERTHSrcElem &&
8633 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8634 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8635 FoundCandidate = true;
8636 break;
8637 }
8638 } else { // If both operands are defined.
8639 // Target order is [8,15] if the current mask is between [0,7].
8640 TargetOrder =
8641 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8642 // Skip if mask of other elements don't equal our expected order.
8643 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8644 // We only need the last 3 bits for the number of shifts.
8645 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8646 : BigEndianShifts[MaskOneElt & 0x7];
8647 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8648 Swap = MaskOneElt < NumHalfWords;
8649 FoundCandidate = true;
8650 break;
8651 }
8652 }
8653 }
8654
8655 if (!FoundCandidate)
8656 return SDValue();
8657
8658 // Candidate found, construct the proper SDAG sequence with VINSERTH,
8659 // optionally with VECSHL if shift is required.
8660 if (Swap)
8661 std::swap(V1, V2);
8662 if (V2.isUndef())
8663 V2 = V1;
8664 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8665 if (ShiftElts) {
8666 // Double ShiftElts because we're left shifting on v16i8 type.
8667 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8668 DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8669 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8670 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8671 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8672 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8673 }
8674 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8675 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8676 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8677 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8678}
8679
8680/// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
8681/// is a shuffle we can handle in a single instruction, return it. Otherwise,
8682/// return the code it can be lowered into. Worst case, it can always be
8683/// lowered into a vperm.
8684SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8685 SelectionDAG &DAG) const {
8686 SDLoc dl(Op);
8687 SDValue V1 = Op.getOperand(0);
8688 SDValue V2 = Op.getOperand(1);
8689 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8690 EVT VT = Op.getValueType();
8691 bool isLittleEndian = Subtarget.isLittleEndian();
8692
8693 unsigned ShiftElts, InsertAtByte;
8694 bool Swap = false;
8695 if (Subtarget.hasP9Vector() &&
8696 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8697 isLittleEndian)) {
8698 if (Swap)
8699 std::swap(V1, V2);
8700 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8701 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8702 if (ShiftElts) {
8703 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8704 DAG.getConstant(ShiftElts, dl, MVT::i32));
8705 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8706 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8707 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8708 }
8709 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8710 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8711 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8712 }
8713
8714 if (Subtarget.hasP9Altivec()) {
8715 SDValue NewISDNode;
8716 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8717 return NewISDNode;
8718
8719 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8720 return NewISDNode;
8721 }
8722
8723 if (Subtarget.hasVSX() &&
8724 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8725 if (Swap)
8726 std::swap(V1, V2);
8727 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8728 SDValue Conv2 =
8729 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8730
8731 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8732 DAG.getConstant(ShiftElts, dl, MVT::i32));
8733 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8734 }
8735
8736 if (Subtarget.hasVSX() &&
8737 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8738 if (Swap)
8739 std::swap(V1, V2);
8740 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8741 SDValue Conv2 =
8742 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8743
8744 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8745 DAG.getConstant(ShiftElts, dl, MVT::i32));
8746 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8747 }
8748
8749 if (Subtarget.hasP9Vector()) {
8750 if (PPC::isXXBRHShuffleMask(SVOp)) {
8751 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8752 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8753 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8754 } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8755 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8756 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8757 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8758 } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8759 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8760 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8761 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8762 } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8763 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8764 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8765 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8766 }
8767 }
8768
8769 if (Subtarget.hasVSX()) {
8770 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8771 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8772
8773 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8774 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8775 DAG.getConstant(SplatIdx, dl, MVT::i32));
8776 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8777 }
8778
8779 // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8780 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8781 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8782 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8783 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8784 }
8785 }
8786
8787 if (Subtarget.hasQPX()) {
8788 if (VT.getVectorNumElements() != 4)
8789 return SDValue();
8790
8791 if (V2.isUndef()) V2 = V1;
8792
8793 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8794 if (AlignIdx != -1) {
8795 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8796 DAG.getConstant(AlignIdx, dl, MVT::i32));
8797 } else if (SVOp->isSplat()) {
8798 int SplatIdx = SVOp->getSplatIndex();
8799 if (SplatIdx >= 4) {
8800 std::swap(V1, V2);
8801 SplatIdx -= 4;
8802 }
8803
8804 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8805 DAG.getConstant(SplatIdx, dl, MVT::i32));
8806 }
8807
8808 // Lower this into a qvgpci/qvfperm pair.
8809
8810 // Compute the qvgpci literal
8811 unsigned idx = 0;
8812 for (unsigned i = 0; i < 4; ++i) {
8813 int m = SVOp->getMaskElt(i);
8814 unsigned mm = m >= 0 ? (unsigned) m : i;
8815 idx |= mm << (3-i)*3;
8816 }
8817
8818 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8819 DAG.getConstant(idx, dl, MVT::i32));
8820 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8821 }
8822
8823 // Cases that are handled by instructions that take permute immediates
8824 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8825 // selected by the instruction selector.
8826 if (V2.isUndef()) {
8827 if (PPC::isSplatShuffleMask(SVOp, 1) ||
8828 PPC::isSplatShuffleMask(SVOp, 2) ||
8829 PPC::isSplatShuffleMask(SVOp, 4) ||
8830 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8831 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8832 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8833 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8834 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8835 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8836 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8837 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8838 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8839 (Subtarget.hasP8Altivec() && (
8840 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8841 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8842 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8843 return Op;
8844 }
8845 }
8846
8847 // Altivec has a variety of "shuffle immediates" that take two vector inputs
8848 // and produce a fixed permutation. If any of these match, do not lower to
8849 // VPERM.
8850 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8851 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8852 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8853 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8854 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8855 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8856 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8857 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8858 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8859 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8860 (Subtarget.hasP8Altivec() && (
8861 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8862 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8863 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8864 return Op;
8865
8866 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
8867 // perfect shuffle table to emit an optimal matching sequence.
8868 ArrayRef<int> PermMask = SVOp->getMask();
8869
8870 unsigned PFIndexes[4];
8871 bool isFourElementShuffle = true;
8872 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8873 unsigned EltNo = 8; // Start out undef.
8874 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
8875 if (PermMask[i*4+j] < 0)
8876 continue; // Undef, ignore it.
8877
8878 unsigned ByteSource = PermMask[i*4+j];
8879 if ((ByteSource & 3) != j) {
8880 isFourElementShuffle = false;
8881 break;
8882 }
8883
8884 if (EltNo == 8) {
8885 EltNo = ByteSource/4;
8886 } else if (EltNo != ByteSource/4) {
8887 isFourElementShuffle = false;
8888 break;
8889 }
8890 }
8891 PFIndexes[i] = EltNo;
8892 }
8893
8894 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8895 // perfect shuffle vector to determine if it is cost effective to do this as
8896 // discrete instructions, or whether we should use a vperm.
8897 // For now, we skip this for little endian until such time as we have a
8898 // little-endian perfect shuffle table.
8899 if (isFourElementShuffle && !isLittleEndian) {
8900 // Compute the index in the perfect shuffle table.
8901 unsigned PFTableIndex =
8902 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8903
8904 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8905 unsigned Cost = (PFEntry >> 30);
8906
8907 // Determining when to avoid vperm is tricky. Many things affect the cost
8908 // of vperm, particularly how many times the perm mask needs to be computed.
8909 // For example, if the perm mask can be hoisted out of a loop or is already
8910 // used (perhaps because there are multiple permutes with the same shuffle
8911 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
8912 // the loop requires an extra register.
8913 //
8914 // As a compromise, we only emit discrete instructions if the shuffle can be
8915 // generated in 3 or fewer operations. When we have loop information
8916 // available, if this block is within a loop, we should avoid using vperm
8917 // for 3-operation perms and use a constant pool load instead.
8918 if (Cost < 3)
8919 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8920 }
8921
8922 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8923 // vector that will get spilled to the constant pool.
8924 if (V2.isUndef()) V2 = V1;
8925
8926 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8927 // that it is in input element units, not in bytes. Convert now.
8928
8929 // For little endian, the order of the input vectors is reversed, and
8930 // the permutation mask is complemented with respect to 31. This is
8931 // necessary to produce proper semantics with the big-endian-biased vperm
8932 // instruction.
8933 EVT EltVT = V1.getValueType().getVectorElementType();
8934 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8935
8936 SmallVector<SDValue, 16> ResultMask;
8937 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8938 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8939
8940 for (unsigned j = 0; j != BytesPerElement; ++j)
8941 if (isLittleEndian)
8942 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8943 dl, MVT::i32));
8944 else
8945 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8946 MVT::i32));
8947 }
8948
8949 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
8950 if (isLittleEndian)
8951 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8952 V2, V1, VPermMask);
8953 else
8954 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8955 V1, V2, VPermMask);
8956}
8957
8958/// getVectorCompareInfo - Given an intrinsic, return false if it is not a
8959/// vector comparison. If it is, return true and fill in Opc/isDot with
8960/// information about the intrinsic.
8961static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
8962 bool &isDot, const PPCSubtarget &Subtarget) {
8963 unsigned IntrinsicID =
8964 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
8965 CompareOpc = -1;
8966 isDot = false;
8967 switch (IntrinsicID) {
8968 default:
8969 return false;
8970 // Comparison predicates.
8971 case Intrinsic::ppc_altivec_vcmpbfp_p:
8972 CompareOpc = 966;
8973 isDot = true;
8974 break;
8975 case Intrinsic::ppc_altivec_vcmpeqfp_p:
8976 CompareOpc = 198;
8977 isDot = true;
8978 break;
8979 case Intrinsic::ppc_altivec_vcmpequb_p:
8980 CompareOpc = 6;
8981 isDot = true;
8982 break;
8983 case Intrinsic::ppc_altivec_vcmpequh_p:
8984 CompareOpc = 70;
8985 isDot = true;
8986 break;
8987 case Intrinsic::ppc_altivec_vcmpequw_p:
8988 CompareOpc = 134;
8989 isDot = true;
8990 break;
8991 case Intrinsic::ppc_altivec_vcmpequd_p:
8992 if (Subtarget.hasP8Altivec()) {
8993 CompareOpc = 199;
8994 isDot = true;
8995 } else
8996 return false;
8997 break;
8998 case Intrinsic::ppc_altivec_vcmpneb_p:
8999 case Intrinsic::ppc_altivec_vcmpneh_p:
9000 case Intrinsic::ppc_altivec_vcmpnew_p:
9001 case Intrinsic::ppc_altivec_vcmpnezb_p:
9002 case Intrinsic::ppc_altivec_vcmpnezh_p:
9003 case Intrinsic::ppc_altivec_vcmpnezw_p:
9004 if (Subtarget.hasP9Altivec()) {
9005 switch (IntrinsicID) {
9006 default:
9007 llvm_unreachable("Unknown comparison intrinsic.");
9008 case Intrinsic::ppc_altivec_vcmpneb_p:
9009 CompareOpc = 7;
9010 break;
9011 case Intrinsic::ppc_altivec_vcmpneh_p:
9012 CompareOpc = 71;
9013 break;
9014 case Intrinsic::ppc_altivec_vcmpnew_p:
9015 CompareOpc = 135;
9016 break;
9017 case Intrinsic::ppc_altivec_vcmpnezb_p:
9018 CompareOpc = 263;
9019 break;
9020 case Intrinsic::ppc_altivec_vcmpnezh_p:
9021 CompareOpc = 327;
9022 break;
9023 case Intrinsic::ppc_altivec_vcmpnezw_p:
9024 CompareOpc = 391;
9025 break;
9026 }
9027 isDot = true;
9028 } else
9029 return false;
9030 break;
9031 case Intrinsic::ppc_altivec_vcmpgefp_p:
9032 CompareOpc = 454;
9033 isDot = true;
9034 break;
9035 case Intrinsic::ppc_altivec_vcmpgtfp_p:
9036 CompareOpc = 710;
9037 isDot = true;
9038 break;
9039 case Intrinsic::ppc_altivec_vcmpgtsb_p:
9040 CompareOpc = 774;
9041 isDot = true;
9042 break;
9043 case Intrinsic::ppc_altivec_vcmpgtsh_p:
9044 CompareOpc = 838;
9045 isDot = true;
9046 break;
9047 case Intrinsic::ppc_altivec_vcmpgtsw_p:
9048 CompareOpc = 902;
9049 isDot = true;
9050 break;
9051 case Intrinsic::ppc_altivec_vcmpgtsd_p:
9052 if (Subtarget.hasP8Altivec()) {
9053 CompareOpc = 967;
9054 isDot = true;
9055 } else
9056 return false;
9057 break;
9058 case Intrinsic::ppc_altivec_vcmpgtub_p:
9059 CompareOpc = 518;
9060 isDot = true;
9061 break;
9062 case Intrinsic::ppc_altivec_vcmpgtuh_p:
9063 CompareOpc = 582;
9064 isDot = true;
9065 break;
9066 case Intrinsic::ppc_altivec_vcmpgtuw_p:
9067 CompareOpc = 646;
9068 isDot = true;
9069 break;
9070 case Intrinsic::ppc_altivec_vcmpgtud_p:
9071 if (Subtarget.hasP8Altivec()) {
9072 CompareOpc = 711;
9073 isDot = true;
9074 } else
9075 return false;
9076 break;
9077
9078 // VSX predicate comparisons use the same infrastructure
9079 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9080 case Intrinsic::ppc_vsx_xvcmpgedp_p:
9081 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9082 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9083 case Intrinsic::ppc_vsx_xvcmpgesp_p:
9084 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9085 if (Subtarget.hasVSX()) {
9086 switch (IntrinsicID) {
9087 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9088 CompareOpc = 99;
9089 break;
9090 case Intrinsic::ppc_vsx_xvcmpgedp_p:
9091 CompareOpc = 115;
9092 break;
9093 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9094 CompareOpc = 107;
9095 break;
9096 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9097 CompareOpc = 67;
9098 break;
9099 case Intrinsic::ppc_vsx_xvcmpgesp_p:
9100 CompareOpc = 83;
9101 break;
9102 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9103 CompareOpc = 75;
9104 break;
9105 }
9106 isDot = true;
9107 } else
9108 return false;
9109 break;
9110
9111 // Normal Comparisons.
9112 case Intrinsic::ppc_altivec_vcmpbfp:
9113 CompareOpc = 966;
9114 break;
9115 case Intrinsic::ppc_altivec_vcmpeqfp:
9116 CompareOpc = 198;
9117 break;
9118 case Intrinsic::ppc_altivec_vcmpequb:
9119 CompareOpc = 6;
9120 break;
9121 case Intrinsic::ppc_altivec_vcmpequh:
9122 CompareOpc = 70;
9123 break;
9124 case Intrinsic::ppc_altivec_vcmpequw:
9125 CompareOpc = 134;
9126 break;
9127 case Intrinsic::ppc_altivec_vcmpequd:
9128 if (Subtarget.hasP8Altivec())
9129 CompareOpc = 199;
9130 else
9131 return false;
9132 break;
9133 case Intrinsic::ppc_altivec_vcmpneb:
9134 case Intrinsic::ppc_altivec_vcmpneh:
9135 case Intrinsic::ppc_altivec_vcmpnew:
9136 case Intrinsic::ppc_altivec_vcmpnezb:
9137 case Intrinsic::ppc_altivec_vcmpnezh:
9138 case Intrinsic::ppc_altivec_vcmpnezw:
9139 if (Subtarget.hasP9Altivec())
9140 switch (IntrinsicID) {
9141 default:
9142 llvm_unreachable("Unknown comparison intrinsic.");
9143 case Intrinsic::ppc_altivec_vcmpneb:
9144 CompareOpc = 7;
9145 break;
9146 case Intrinsic::ppc_altivec_vcmpneh:
9147 CompareOpc = 71;
9148 break;
9149 case Intrinsic::ppc_altivec_vcmpnew:
9150 CompareOpc = 135;
9151 break;
9152 case Intrinsic::ppc_altivec_vcmpnezb:
9153 CompareOpc = 263;
9154 break;
9155 case Intrinsic::ppc_altivec_vcmpnezh:
9156 CompareOpc = 327;
9157 break;
9158 case Intrinsic::ppc_altivec_vcmpnezw:
9159 CompareOpc = 391;
9160 break;
9161 }
9162 else
9163 return false;
9164 break;
9165 case Intrinsic::ppc_altivec_vcmpgefp:
9166 CompareOpc = 454;
9167 break;
9168 case Intrinsic::ppc_altivec_vcmpgtfp:
9169 CompareOpc = 710;
9170 break;
9171 case Intrinsic::ppc_altivec_vcmpgtsb:
9172 CompareOpc = 774;
9173 break;
9174 case Intrinsic::ppc_altivec_vcmpgtsh:
9175 CompareOpc = 838;
9176 break;
9177 case Intrinsic::ppc_altivec_vcmpgtsw:
9178 CompareOpc = 902;
9179 break;
9180 case Intrinsic::ppc_altivec_vcmpgtsd:
9181 if (Subtarget.hasP8Altivec())
9182 CompareOpc = 967;
9183 else
9184 return false;
9185 break;
9186 case Intrinsic::ppc_altivec_vcmpgtub:
9187 CompareOpc = 518;
9188 break;
9189 case Intrinsic::ppc_altivec_vcmpgtuh:
9190 CompareOpc = 582;
9191 break;
9192 case Intrinsic::ppc_altivec_vcmpgtuw:
9193 CompareOpc = 646;
9194 break;
9195 case Intrinsic::ppc_altivec_vcmpgtud:
9196 if (Subtarget.hasP8Altivec())
9197 CompareOpc = 711;
9198 else
9199 return false;
9200 break;
9201 }
9202 return true;
9203}
9204
9205/// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9206/// lower, do it, otherwise return null.
9207SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9208 SelectionDAG &DAG) const {
9209 unsigned IntrinsicID =
9210 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9211
9212 SDLoc dl(Op);
9213
9214 if (IntrinsicID == Intrinsic::thread_pointer) {
9215 // Reads the thread pointer register, used for __builtin_thread_pointer.
9216 if (Subtarget.isPPC64())
9217 return DAG.getRegister(PPC::X13, MVT::i64);
9218 return DAG.getRegister(PPC::R2, MVT::i32);
9219 }
9220
9221 // If this is a lowered altivec predicate compare, CompareOpc is set to the
9222 // opcode number of the comparison.
9223 int CompareOpc;
9224 bool isDot;
9225 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9226 return SDValue(); // Don't custom lower most intrinsics.
9227
9228 // If this is a non-dot comparison, make the VCMP node and we are done.
9229 if (!isDot) {
9230 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9231 Op.getOperand(1), Op.getOperand(2),
9232 DAG.getConstant(CompareOpc, dl, MVT::i32));
9233 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9234 }
9235
9236 // Create the PPCISD altivec 'dot' comparison node.
9237 SDValue Ops[] = {
9238 Op.getOperand(2), // LHS
9239 Op.getOperand(3), // RHS
9240 DAG.getConstant(CompareOpc, dl, MVT::i32)
9241 };
9242 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9243 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9244
9245 // Now that we have the comparison, emit a copy from the CR to a GPR.
9246 // This is flagged to the above dot comparison.
9247 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9248 DAG.getRegister(PPC::CR6, MVT::i32),
9249 CompNode.getValue(1));
9250
9251 // Unpack the result based on how the target uses it.
9252 unsigned BitNo; // Bit # of CR6.
9253 bool InvertBit; // Invert result?
9254 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9255 default: // Can't happen, don't crash on invalid number though.
9256 case 0: // Return the value of the EQ bit of CR6.
9257 BitNo = 0; InvertBit = false;
9258 break;
9259 case 1: // Return the inverted value of the EQ bit of CR6.
9260 BitNo = 0; InvertBit = true;
9261 break;
9262 case 2: // Return the value of the LT bit of CR6.
9263 BitNo = 2; InvertBit = false;
9264 break;
9265 case 3: // Return the inverted value of the LT bit of CR6.
9266 BitNo = 2; InvertBit = true;
9267 break;
9268 }
9269
9270 // Shift the bit into the low position.
9271 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9272 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9273 // Isolate the bit.
9274 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9275 DAG.getConstant(1, dl, MVT::i32));
9276
9277 // If we are supposed to, toggle the bit.
9278 if (InvertBit)
9279 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9280 DAG.getConstant(1, dl, MVT::i32));
9281 return Flags;
9282}
9283
9284SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9285 SelectionDAG &DAG) const {
9286 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9287 // the beginning of the argument list.
9288 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9289 SDLoc DL(Op);
9290 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9291 case Intrinsic::ppc_cfence: {
9292 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9293 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9294 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9295 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9296 Op.getOperand(ArgStart + 1)),
9297 Op.getOperand(0)),
9298 0);
9299 }
9300 default:
9301 break;
9302 }
9303 return SDValue();
9304}
9305
9306SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9307 // Check for a DIV with the same operands as this REM.
9308 for (auto UI : Op.getOperand(1)->uses()) {
9309 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9310 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9311 if (UI->getOperand(0) == Op.getOperand(0) &&
9312 UI->getOperand(1) == Op.getOperand(1))
9313 return SDValue();
9314 }
9315 return Op;
9316}
9317
9318// Lower scalar BSWAP64 to xxbrd.
9319SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9320 SDLoc dl(Op);
9321 // MTVSRDD
9322 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9323 Op.getOperand(0));
9324 // XXBRD
9325 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
9326 // MFVSRD
9327 int VectorIndex = 0;
9328 if (Subtarget.isLittleEndian())
9329 VectorIndex = 1;
9330 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9331 DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9332 return Op;
9333}
9334
9335// ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9336// compared to a value that is atomically loaded (atomic loads zero-extend).
9337SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9338 SelectionDAG &DAG) const {
9339 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9340 "Expecting an atomic compare-and-swap here.");
9341 SDLoc dl(Op);
9342 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9343 EVT MemVT = AtomicNode->getMemoryVT();
9344 if (MemVT.getSizeInBits() >= 32)
9345 return Op;
9346
9347 SDValue CmpOp = Op.getOperand(2);
9348 // If this is already correctly zero-extended, leave it alone.
9349 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9350 if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9351 return Op;
9352
9353 // Clear the high bits of the compare operand.
9354 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9355 SDValue NewCmpOp =
9356 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9357 DAG.getConstant(MaskVal, dl, MVT::i32));
9358
9359 // Replace the existing compare operand with the properly zero-extended one.
9360 SmallVector<SDValue, 4> Ops;
9361 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9362 Ops.push_back(AtomicNode->getOperand(i));
9363 Ops[2] = NewCmpOp;
9364 MachineMemOperand *MMO = AtomicNode->getMemOperand();
9365 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9366 auto NodeTy =
9367 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9368 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9369}
9370
9371SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9372 SelectionDAG &DAG) const {
9373 SDLoc dl(Op);
9374 // Create a stack slot that is 16-byte aligned.
9375 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9376 int FrameIdx = MFI.CreateStackObject(16, 16, false);
9377 EVT PtrVT = getPointerTy(DAG.getDataLayout());
9378 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9379
9380 // Store the input value into Value#0 of the stack slot.
9381 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9382 MachinePointerInfo());
9383 // Load it out.
9384 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9385}
9386
9387SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9388 SelectionDAG &DAG) const {
9389 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9390 "Should only be called for ISD::INSERT_VECTOR_ELT");
9391
9392 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9393 // We have legal lowering for constant indices but not for variable ones.
9394 if (!C)
9395 return SDValue();
9396
9397 EVT VT = Op.getValueType();
9398 SDLoc dl(Op);
9399 SDValue V1 = Op.getOperand(0);
9400 SDValue V2 = Op.getOperand(1);
9401 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9402 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9403 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9404 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9405 unsigned InsertAtElement = C->getZExtValue();
9406 unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9407 if (Subtarget.isLittleEndian()) {
9408 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9409 }
9410 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9411 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9412 }
9413 return Op;
9414}
9415
9416SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9417 SelectionDAG &DAG) const {
9418 SDLoc dl(Op);
9419 SDNode *N = Op.getNode();
9420
9421 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9422 "Unknown extract_vector_elt type");
9423
9424 SDValue Value = N->getOperand(0);
9425
9426 // The first part of this is like the store lowering except that we don't
9427 // need to track the chain.
9428
9429 // The values are now known to be -1 (false) or 1 (true). To convert this
9430 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9431 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9432 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9433
9434 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9435 // understand how to form the extending load.
9436 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9437
9438 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9439
9440 // Now convert to an integer and store.
9441 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9442 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9443 Value);
9444
9445 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9446 int FrameIdx = MFI.CreateStackObject(16, 16, false);
9447 MachinePointerInfo PtrInfo =
9448 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9449 EVT PtrVT = getPointerTy(DAG.getDataLayout());
9450 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9451
9452 SDValue StoreChain = DAG.getEntryNode();
9453 SDValue Ops[] = {StoreChain,
9454 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9455 Value, FIdx};
9456 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9457
9458 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9459 dl, VTs, Ops, MVT::v4i32, PtrInfo);
9460
9461 // Extract the value requested.
9462 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9463 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9464 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9465
9466 SDValue IntVal =
9467 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9468
9469 if (!Subtarget.useCRBits())
9470 return IntVal;
9471
9472 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9473}
9474
9475/// Lowering for QPX v4i1 loads
9476SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9477 SelectionDAG &DAG) const {
9478 SDLoc dl(Op);
9479 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9480 SDValue LoadChain = LN->getChain();
9481 SDValue BasePtr = LN->getBasePtr();
9482
9483 if (Op.getValueType() == MVT::v4f64 ||
9484 Op.getValueType() == MVT::v4f32) {
9485 EVT MemVT = LN->getMemoryVT();
9486 unsigned Alignment = LN->getAlignment();
9487
9488 // If this load is properly aligned, then it is legal.
9489 if (Alignment >= MemVT.getStoreSize())
9490 return Op;
9491
9492 EVT ScalarVT = Op.getValueType().getScalarType(),
9493 ScalarMemVT = MemVT.getScalarType();
9494 unsigned Stride = ScalarMemVT.getStoreSize();
9495
9496 SDValue Vals[4], LoadChains[4];
9497 for (unsigned Idx = 0; Idx < 4; ++Idx) {
9498 SDValue Load;
9499 if (ScalarVT != ScalarMemVT)
9500 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9501 BasePtr,
9502 LN->getPointerInfo().getWithOffset(Idx * Stride),
9503 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9504 LN->getMemOperand()->getFlags(), LN->getAAInfo());
9505 else
9506 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9507 LN->getPointerInfo().getWithOffset(Idx * Stride),
9508 MinAlign(Alignment, Idx * Stride),
9509 LN->getMemOperand()->getFlags(), LN->getAAInfo());
9510
9511 if (Idx == 0 && LN->isIndexed()) {
9512 assert(LN->getAddressingMode() == ISD::PRE_INC &&
9513 "Unknown addressing mode on vector load");
9514 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9515 LN->getAddressingMode());
9516 }
9517
9518 Vals[Idx] = Load;
9519 LoadChains[Idx] = Load.getValue(1);
9520
9521 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9522 DAG.getConstant(Stride, dl,
9523 BasePtr.getValueType()));
9524 }
9525
9526 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9527 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9528
9529 if (LN->isIndexed()) {
9530 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9531 return DAG.getMergeValues(RetOps, dl);
9532 }
9533
9534 SDValue RetOps[] = { Value, TF };
9535 return DAG.getMergeValues(RetOps, dl);
9536 }
9537
9538 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9539 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9540
9541 // To lower v4i1 from a byte array, we load the byte elements of the
9542 // vector and then reuse the BUILD_VECTOR logic.
9543
9544 SDValue VectElmts[4], VectElmtChains[4];
9545 for (unsigned i = 0; i < 4; ++i) {
9546 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9547 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9548
9549 VectElmts[i] = DAG.getExtLoad(
9550 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9551 LN->getPointerInfo().getWithOffset(i), MVT::i8,
9552 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9553 VectElmtChains[i] = VectElmts[i].getValue(1);
9554 }
9555
9556 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9557 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9558
9559 SDValue RVals[] = { Value, LoadChain };
9560 return DAG.getMergeValues(RVals, dl);
9561}
9562
9563/// Lowering for QPX v4i1 stores
9564SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9565 SelectionDAG &DAG) const {
9566 SDLoc dl(Op);
9567 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9568 SDValue StoreChain = SN->getChain();
9569 SDValue BasePtr = SN->getBasePtr();
9570 SDValue Value = SN->getValue();
9571
9572 if (Value.getValueType() == MVT::v4f64 ||
9573 Value.getValueType() == MVT::v4f32) {
9574 EVT MemVT = SN->getMemoryVT();
9575 unsigned Alignment = SN->getAlignment();
9576
9577 // If this store is properly aligned, then it is legal.
9578 if (Alignment >= MemVT.getStoreSize())
9579 return Op;
9580
9581 EVT ScalarVT = Value.getValueType().getScalarType(),
9582 ScalarMemVT = MemVT.getScalarType();
9583 unsigned Stride = ScalarMemVT.getStoreSize();
9584
9585 SDValue Stores[4];
9586 for (unsigned Idx = 0; Idx < 4; ++Idx) {
9587 SDValue Ex = DAG.getNode(
9588 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9589 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9590 SDValue Store;
9591 if (ScalarVT != ScalarMemVT)
9592 Store =
9593 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9594 SN->getPointerInfo().getWithOffset(Idx * Stride),
9595 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9596 SN->getMemOperand()->getFlags(), SN->getAAInfo());
9597 else
9598 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9599 SN->getPointerInfo().getWithOffset(Idx * Stride),
9600 MinAlign(Alignment, Idx * Stride),
9601 SN->getMemOperand()->getFlags(), SN->getAAInfo());
9602
9603 if (Idx == 0 && SN->isIndexed()) {
9604 assert(SN->getAddressingMode() == ISD::PRE_INC &&
9605 "Unknown addressing mode on vector store");
9606 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9607 SN->getAddressingMode());
9608 }
9609
9610 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9611 DAG.getConstant(Stride, dl,
9612 BasePtr.getValueType()));
9613 Stores[Idx] = Store;
9614 }
9615
9616 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9617
9618 if (SN->isIndexed()) {
9619 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9620 return DAG.getMergeValues(RetOps, dl);
9621 }
9622
9623 return TF;
9624 }
9625
9626 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9627 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9628
9629 // The values are now known to be -1 (false) or 1 (true). To convert this
9630 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9631 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9632 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9633
9634 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9635 // understand how to form the extending load.
9636 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9637
9638 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9639
9640 // Now convert to an integer and store.
9641 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9642 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9643 Value);
9644
9645 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9646 int FrameIdx = MFI.CreateStackObject(16, 16, false);
9647 MachinePointerInfo PtrInfo =
9648 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9649 EVT PtrVT = getPointerTy(DAG.getDataLayout());
9650 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9651
9652 SDValue Ops[] = {StoreChain,
9653 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9654 Value, FIdx};
9655 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9656
9657 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9658 dl, VTs, Ops, MVT::v4i32, PtrInfo);
9659
9660 // Move data into the byte array.
9661 SDValue Loads[4], LoadChains[4];
9662 for (unsigned i = 0; i < 4; ++i) {
9663 unsigned Offset = 4*i;
9664 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9665 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9666
9667 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9668 PtrInfo.getWithOffset(Offset));
9669 LoadChains[i] = Loads[i].getValue(1);
9670 }
9671
9672 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9673
9674 SDValue Stores[4];
9675 for (unsigned i = 0; i < 4; ++i) {
9676 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9677 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9678
9679 Stores[i] = DAG.getTruncStore(
9680 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9681 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9682 SN->getAAInfo());
9683 }
9684
9685 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9686
9687 return StoreChain;
9688}
9689
9690SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9691 SDLoc dl(Op);
9692 if (Op.getValueType() == MVT::v4i32) {
9693 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9694
9695 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
9696 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9697
9698 SDValue RHSSwap = // = vrlw RHS, 16
9699 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9700
9701 // Shrinkify inputs to v8i16.
9702 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9703 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9704 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9705
9706 // Low parts multiplied together, generating 32-bit results (we ignore the
9707 // top parts).
9708 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9709 LHS, RHS, DAG, dl, MVT::v4i32);
9710
9711 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9712 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9713 // Shift the high parts up 16 bits.
9714 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9715 Neg16, DAG, dl);
9716 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9717 } else if (Op.getValueType() == MVT::v8i16) {
9718 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9719
9720 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9721
9722 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9723 LHS, RHS, Zero, DAG, dl);
9724 } else if (Op.getValueType() == MVT::v16i8) {
9725 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9726 bool isLittleEndian = Subtarget.isLittleEndian();
9727
9728 // Multiply the even 8-bit parts, producing 16-bit sums.
9729 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9730 LHS, RHS, DAG, dl, MVT::v8i16);
9731 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9732
9733 // Multiply the odd 8-bit parts, producing 16-bit sums.
9734 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9735 LHS, RHS, DAG, dl, MVT::v8i16);
9736 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9737
9738 // Merge the results together. Because vmuleub and vmuloub are
9739 // instructions with a big-endian bias, we must reverse the
9740 // element numbering and reverse the meaning of "odd" and "even"
9741 // when generating little endian code.
9742 int Ops[16];
9743 for (unsigned i = 0; i != 8; ++i) {
9744 if (isLittleEndian) {
9745 Ops[i*2 ] = 2*i;
9746 Ops[i*2+1] = 2*i+16;
9747 } else {
9748 Ops[i*2 ] = 2*i+1;
9749 Ops[i*2+1] = 2*i+1+16;
9750 }
9751 }
9752 if (isLittleEndian)
9753 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9754 else
9755 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9756 } else {
9757 llvm_unreachable("Unknown mul to lower!");
9758 }
9759}
9760
9761SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
9762
9763 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
9764
9765 EVT VT = Op.getValueType();
9766 assert(VT.isVector() &&
9767 "Only set vector abs as custom, scalar abs shouldn't reach here!");
9768 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
9769 VT == MVT::v16i8) &&
9770 "Unexpected vector element type!");
9771 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
9772 "Current subtarget doesn't support smax v2i64!");
9773
9774 // For vector abs, it can be lowered to:
9775 // abs x
9776 // ==>
9777 // y = -x
9778 // smax(x, y)
9779
9780 SDLoc dl(Op);
9781 SDValue X = Op.getOperand(0);
9782 SDValue Zero = DAG.getConstant(0, dl, VT);
9783 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
9784
9785 // SMAX patch https://reviews.llvm.org/D47332
9786 // hasn't landed yet, so use intrinsic first here.
9787 // TODO: Should use SMAX directly once SMAX patch landed
9788 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
9789 if (VT == MVT::v2i64)
9790 BifID = Intrinsic::ppc_altivec_vmaxsd;
9791 else if (VT == MVT::v8i16)
9792 BifID = Intrinsic::ppc_altivec_vmaxsh;
9793 else if (VT == MVT::v16i8)
9794 BifID = Intrinsic::ppc_altivec_vmaxsb;
9795
9796 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
9797}
9798
9799// Custom lowering for fpext vf32 to v2f64
9800SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
9801
9802 assert(Op.getOpcode() == ISD::FP_EXTEND &&
9803 "Should only be called for ISD::FP_EXTEND");
9804
9805 // We only want to custom lower an extend from v2f32 to v2f64.
9806 if (Op.getValueType() != MVT::v2f64 ||
9807 Op.getOperand(0).getValueType() != MVT::v2f32)
9808 return SDValue();
9809
9810 SDLoc dl(Op);
9811 SDValue Op0 = Op.getOperand(0);
9812
9813 switch (Op0.getOpcode()) {
9814 default:
9815 return SDValue();
9816 case ISD::FADD:
9817 case ISD::FMUL:
9818 case ISD::FSUB: {
9819 SDValue NewLoad[2];
9820 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
9821 // Ensure both input are loads.
9822 SDValue LdOp = Op0.getOperand(i);
9823 if (LdOp.getOpcode() != ISD::LOAD)
9824 return SDValue();
9825 // Generate new load node.
9826 LoadSDNode *LD = cast<LoadSDNode>(LdOp);
9827 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() };
9828 NewLoad[i] =
9829 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl,
9830 DAG.getVTList(MVT::v4f32, MVT::Other),
9831 LoadOps, LD->getMemoryVT(),
9832 LD->getMemOperand());
9833 }
9834 SDValue NewOp = DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32,
9835 NewLoad[0], NewLoad[1],
9836 Op0.getNode()->getFlags());
9837 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewOp);
9838 }
9839 case ISD::LOAD: {
9840 LoadSDNode *LD = cast<LoadSDNode>(Op0);
9841 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() };
9842 SDValue NewLd =
9843 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl,
9844 DAG.getVTList(MVT::v4f32, MVT::Other),
9845 LoadOps, LD->getMemoryVT(), LD->getMemOperand());
9846 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewLd);
9847 }
9848 }
9849 llvm_unreachable("ERROR:Should return for all cases within swtich.");
9850}
9851
9852/// LowerOperation - Provide custom lowering hooks for some operations.
9853///
9854SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9855 switch (Op.getOpcode()) {
9856 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9857 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9858 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9859 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9860 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9861 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9862 case ISD::SETCC: return LowerSETCC(Op, DAG);
9863 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
9864 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
9865
9866 // Variable argument lowering.
9867 case ISD::VASTART: return LowerVASTART(Op, DAG);
9868 case ISD::VAARG: return LowerVAARG(Op, DAG);
9869 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9870
9871 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG);
9872 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9873 case ISD::GET_DYNAMIC_AREA_OFFSET:
9874 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9875
9876 // Exception handling lowering.
9877 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG);
9878 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
9879 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
9880
9881 case ISD::LOAD: return LowerLOAD(Op, DAG);
9882 case ISD::STORE: return LowerSTORE(Op, DAG);
9883 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
9884 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
9885 case ISD::FP_TO_UINT:
9886 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
9887 case ISD::UINT_TO_FP:
9888 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
9889 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9890
9891 // Lower 64-bit shifts.
9892 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
9893 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
9894 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
9895
9896 // Vector-related lowering.
9897 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9898 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9899 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9900 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9901 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9902 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9903 case ISD::MUL: return LowerMUL(Op, DAG);
9904 case ISD::ABS: return LowerABS(Op, DAG);
9905 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9906
9907 // For counter-based loop handling.
9908 case ISD::INTRINSIC_W_CHAIN: return SDValue();
9909
9910 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9911
9912 // Frame & Return address.
9913 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9914 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9915
9916 case ISD::INTRINSIC_VOID:
9917 return LowerINTRINSIC_VOID(Op, DAG);
9918 case ISD::SREM:
9919 case ISD::UREM:
9920 return LowerREM(Op, DAG);
9921 case ISD::BSWAP:
9922 return LowerBSWAP(Op, DAG);
9923 case ISD::ATOMIC_CMP_SWAP:
9924 return LowerATOMIC_CMP_SWAP(Op, DAG);
9925 }
9926}
9927
9928void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9929 SmallVectorImpl<SDValue>&Results,
9930 SelectionDAG &DAG) const {
9931 SDLoc dl(N);
9932 switch (N->getOpcode()) {
9933 default:
9934 llvm_unreachable("Do not know how to custom type legalize this operation!");
9935 case ISD::READCYCLECOUNTER: {
9936 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9937 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9938
9939 Results.push_back(RTB);
9940 Results.push_back(RTB.getValue(1));
9941 Results.push_back(RTB.getValue(2));
9942 break;
9943 }
9944 case ISD::INTRINSIC_W_CHAIN: {
9945 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9946 Intrinsic::loop_decrement)
9947 break;
9948
9949 assert(N->getValueType(0) == MVT::i1 &&
9950 "Unexpected result type for CTR decrement intrinsic");
9951 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
9952 N->getValueType(0));
9953 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
9954 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
9955 N->getOperand(1));
9956
9957 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
9958 Results.push_back(NewInt.getValue(1));
9959 break;
9960 }
9961 case ISD::VAARG: {
9962 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
9963 return;
9964
9965 EVT VT = N->getValueType(0);
9966
9967 if (VT == MVT::i64) {
9968 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
9969
9970 Results.push_back(NewNode);
9971 Results.push_back(NewNode.getValue(1));
9972 }
9973 return;
9974 }
9975 case ISD::FP_TO_SINT:
9976 case ISD::FP_TO_UINT:
9977 // LowerFP_TO_INT() can only handle f32 and f64.
9978 if (N->getOperand(0).getValueType() == MVT::ppcf128)
9979 return;
9980 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
9981 return;
9982 case ISD::TRUNCATE: {
9983 EVT TrgVT = N->getValueType(0);
9984 if (TrgVT.isVector() &&
9985 isOperationCustom(N->getOpcode(), TrgVT) &&
9986 N->getOperand(0).getValueType().getSizeInBits() <= 128)
9987 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
9988 return;
9989 }
9990 case ISD::BITCAST:
9991 // Don't handle bitcast here.
9992 return;
9993 }
9994}
9995
9996//===----------------------------------------------------------------------===//
9997// Other Lowering Code
9998//===----------------------------------------------------------------------===//
9999
10000static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10001 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10002 Function *Func = Intrinsic::getDeclaration(M, Id);
10003 return Builder.CreateCall(Func, {});
10004}
10005
10006// The mappings for emitLeading/TrailingFence is taken from
10007// http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10008Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10009 Instruction *Inst,
10010 AtomicOrdering Ord) const {
10011 if (Ord == AtomicOrdering::SequentiallyConsistent)
10012 return callIntrinsic(Builder, Intrinsic::ppc_sync);
10013 if (isReleaseOrStronger(Ord))
10014 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10015 return nullptr;
10016}
10017
10018Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10019 Instruction *Inst,
10020 AtomicOrdering Ord) const {
10021 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10022 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10023 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10024 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10025 if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10026 return Builder.CreateCall(
10027 Intrinsic::getDeclaration(
10028 Builder.GetInsertBlock()->getParent()->getParent(),
10029 Intrinsic::ppc_cfence, {Inst->getType()}),
10030 {Inst});
10031 // FIXME: Can use isync for rmw operation.
10032 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10033 }
10034 return nullptr;
10035}
10036
10037MachineBasicBlock *
10038PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10039 unsigned AtomicSize,
10040 unsigned BinOpcode,
10041 unsigned CmpOpcode,
10042 unsigned CmpPred) const {
10043 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10044 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10045
10046 auto LoadMnemonic = PPC::LDARX;
10047 auto StoreMnemonic = PPC::STDCX;
10048 switch (AtomicSize) {
10049 default:
10050 llvm_unreachable("Unexpected size of atomic entity");
10051 case 1:
10052 LoadMnemonic = PPC::LBARX;
10053 StoreMnemonic = PPC::STBCX;
10054 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10055 break;
10056 case 2:
10057 LoadMnemonic = PPC::LHARX;
10058 StoreMnemonic = PPC::STHCX;
10059 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10060 break;
10061 case 4:
10062 LoadMnemonic = PPC::LWARX;
10063 StoreMnemonic = PPC::STWCX;
10064 break;
10065 case 8:
10066 LoadMnemonic = PPC::LDARX;
10067 StoreMnemonic = PPC::STDCX;
10068 break;
10069 }
10070
10071 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10072 MachineFunction *F = BB->getParent();
10073 MachineFunction::iterator It = ++BB->getIterator();
10074
10075 unsigned dest = MI.getOperand(0).getReg();
10076 unsigned ptrA = MI.getOperand(1).getReg();
10077 unsigned ptrB = MI.getOperand(2).getReg();
10078 unsigned incr = MI.getOperand(3).getReg();
10079 DebugLoc dl = MI.getDebugLoc();
10080
10081 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10082 MachineBasicBlock *loop2MBB =
10083 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10084 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10085 F->insert(It, loopMBB);
10086 if (CmpOpcode)
10087 F->insert(It, loop2MBB);
10088 F->insert(It, exitMBB);
10089 exitMBB->splice(exitMBB->begin(), BB,
10090 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10091 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10092
10093 MachineRegisterInfo &RegInfo = F->getRegInfo();
10094 unsigned TmpReg = (!BinOpcode) ? incr :
10095 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10096 : &PPC::GPRCRegClass);
10097
10098 // thisMBB:
10099 // ...
10100 // fallthrough --> loopMBB
10101 BB->addSuccessor(loopMBB);
10102
10103 // loopMBB:
10104 // l[wd]arx dest, ptr
10105 // add r0, dest, incr
10106 // st[wd]cx. r0, ptr
10107 // bne- loopMBB
10108 // fallthrough --> exitMBB
10109
10110 // For max/min...
10111 // loopMBB:
10112 // l[wd]arx dest, ptr
10113 // cmpl?[wd] incr, dest
10114 // bgt exitMBB
10115 // loop2MBB:
10116 // st[wd]cx. dest, ptr
10117 // bne- loopMBB
10118 // fallthrough --> exitMBB
10119
10120 BB = loopMBB;
10121 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10122 .addReg(ptrA).addReg(ptrB);
10123 if (BinOpcode)
10124 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10125 if (CmpOpcode) {
10126 // Signed comparisons of byte or halfword values must be sign-extended.
10127 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10128 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10129 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10130 ExtReg).addReg(dest);
10131 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10132 .addReg(incr).addReg(ExtReg);
10133 } else
10134 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10135 .addReg(incr).addReg(dest);
10136
10137 BuildMI(BB, dl, TII->get(PPC::BCC))
10138 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10139 BB->addSuccessor(loop2MBB);
10140 BB->addSuccessor(exitMBB);
10141 BB = loop2MBB;
10142 }
10143 BuildMI(BB, dl, TII->get(StoreMnemonic))
10144 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10145 BuildMI(BB, dl, TII->get(PPC::BCC))
10146 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10147 BB->addSuccessor(loopMBB);
10148 BB->addSuccessor(exitMBB);
10149
10150 // exitMBB:
10151 // ...
10152 BB = exitMBB;
10153 return BB;
10154}
10155
10156MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10157 MachineInstr &MI, MachineBasicBlock *BB,
10158 bool is8bit, // operation
10159 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10160 // If we support part-word atomic mnemonics, just use them
10161 if (Subtarget.hasPartwordAtomics())
10162 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10163 CmpPred);
10164
10165 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10166 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10167 // In 64 bit mode we have to use 64 bits for addresses, even though the
10168 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
10169 // registers without caring whether they're 32 or 64, but here we're
10170 // doing actual arithmetic on the addresses.
10171 bool is64bit = Subtarget.isPPC64();
10172 bool isLittleEndian = Subtarget.isLittleEndian();
10173 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10174
10175 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10176 MachineFunction *F = BB->getParent();
10177 MachineFunction::iterator It = ++BB->getIterator();
10178
10179 unsigned dest = MI.getOperand(0).getReg();
10180 unsigned ptrA = MI.getOperand(1).getReg();
10181 unsigned ptrB = MI.getOperand(2).getReg();
10182 unsigned incr = MI.getOperand(3).getReg();
10183 DebugLoc dl = MI.getDebugLoc();
10184
10185 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10186 MachineBasicBlock *loop2MBB =
10187 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10188 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10189 F->insert(It, loopMBB);
10190 if (CmpOpcode)
10191 F->insert(It, loop2MBB);
10192 F->insert(It, exitMBB);
10193 exitMBB->splice(exitMBB->begin(), BB,
10194 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10195 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10196
10197 MachineRegisterInfo &RegInfo = F->getRegInfo();
10198 const TargetRegisterClass *RC =
10199 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10200 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10201
10202 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10203 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10204 unsigned ShiftReg =
10205 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10206 unsigned Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10207 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC);
10208 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10209 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10210 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10211 unsigned Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10212 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10213 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10214 unsigned Ptr1Reg;
10215 unsigned TmpReg =
10216 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10217
10218 // thisMBB:
10219 // ...
10220 // fallthrough --> loopMBB
10221 BB->addSuccessor(loopMBB);
10222
10223 // The 4-byte load must be aligned, while a char or short may be
10224 // anywhere in the word. Hence all this nasty bookkeeping code.
10225 // add ptr1, ptrA, ptrB [copy if ptrA==0]
10226 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10227 // xori shift, shift1, 24 [16]
10228 // rlwinm ptr, ptr1, 0, 0, 29
10229 // slw incr2, incr, shift
10230 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10231 // slw mask, mask2, shift
10232 // loopMBB:
10233 // lwarx tmpDest, ptr
10234 // add tmp, tmpDest, incr2
10235 // andc tmp2, tmpDest, mask
10236 // and tmp3, tmp, mask
10237 // or tmp4, tmp3, tmp2
10238 // stwcx. tmp4, ptr
10239 // bne- loopMBB
10240 // fallthrough --> exitMBB
10241 // srw dest, tmpDest, shift
10242 if (ptrA != ZeroReg) {
10243 Ptr1Reg = RegInfo.createVirtualRegister(RC);
10244 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10245 .addReg(ptrA)
10246 .addReg(ptrB);
10247 } else {
10248 Ptr1Reg = ptrB;
10249 }
10250 // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10251 // mode.
10252 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10253 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10254 .addImm(3)
10255 .addImm(27)
10256 .addImm(is8bit ? 28 : 27);
10257 if (!isLittleEndian)
10258 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10259 .addReg(Shift1Reg)
10260 .addImm(is8bit ? 24 : 16);
10261 if (is64bit)
10262 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10263 .addReg(Ptr1Reg)
10264 .addImm(0)
10265 .addImm(61);
10266 else
10267 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10268 .addReg(Ptr1Reg)
10269 .addImm(0)
10270 .addImm(0)
10271 .addImm(29);
10272 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10273 if (is8bit)
10274 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10275 else {
10276 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10277 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10278 .addReg(Mask3Reg)
10279 .addImm(65535);
10280 }
10281 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10282 .addReg(Mask2Reg)
10283 .addReg(ShiftReg);
10284
10285 BB = loopMBB;
10286 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10287 .addReg(ZeroReg)
10288 .addReg(PtrReg);
10289 if (BinOpcode)
10290 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10291 .addReg(Incr2Reg)
10292 .addReg(TmpDestReg);
10293 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10294 .addReg(TmpDestReg)
10295 .addReg(MaskReg);
10296 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10297 if (CmpOpcode) {
10298 // For unsigned comparisons, we can directly compare the shifted values.
10299 // For signed comparisons we shift and sign extend.
10300 unsigned SReg = RegInfo.createVirtualRegister(GPRC);
10301 BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10302 .addReg(TmpDestReg)
10303 .addReg(MaskReg);
10304 unsigned ValueReg = SReg;
10305 unsigned CmpReg = Incr2Reg;
10306 if (CmpOpcode == PPC::CMPW) {
10307 ValueReg = RegInfo.createVirtualRegister(GPRC);
10308 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10309 .addReg(SReg)
10310 .addReg(ShiftReg);
10311 unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC);
10312 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10313 .addReg(ValueReg);
10314 ValueReg = ValueSReg;
10315 CmpReg = incr;
10316 }
10317 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10318 .addReg(CmpReg)
10319 .addReg(ValueReg);
10320 BuildMI(BB, dl, TII->get(PPC::BCC))
10321 .addImm(CmpPred)
10322 .addReg(PPC::CR0)
10323 .addMBB(exitMBB);
10324 BB->addSuccessor(loop2MBB);
10325 BB->addSuccessor(exitMBB);
10326 BB = loop2MBB;
10327 }
10328 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10329 BuildMI(BB, dl, TII->get(PPC::STWCX))
10330 .addReg(Tmp4Reg)
10331 .addReg(ZeroReg)
10332 .addReg(PtrReg);
10333 BuildMI(BB, dl, TII->get(PPC::BCC))
10334 .addImm(PPC::PRED_NE)
10335 .addReg(PPC::CR0)
10336 .addMBB(loopMBB);
10337 BB->addSuccessor(loopMBB);
10338 BB->addSuccessor(exitMBB);
10339
10340 // exitMBB:
10341 // ...
10342 BB = exitMBB;
10343 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10344 .addReg(TmpDestReg)
10345 .addReg(ShiftReg);
10346 return BB;
10347}
10348
10349llvm::MachineBasicBlock *
10350PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10351 MachineBasicBlock *MBB) const {
10352 DebugLoc DL = MI.getDebugLoc();
10353 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10354 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10355
10356 MachineFunction *MF = MBB->getParent();
10357 MachineRegisterInfo &MRI = MF->getRegInfo();
10358
10359 const BasicBlock *BB = MBB->getBasicBlock();
10360 MachineFunction::iterator I = ++MBB->getIterator();
10361
10362 unsigned DstReg = MI.getOperand(0).getReg();
10363 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10364 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10365 unsigned mainDstReg = MRI.createVirtualRegister(RC);
10366 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
10367
10368 MVT PVT = getPointerTy(MF->getDataLayout());
10369 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10370 "Invalid Pointer Size!");
10371 // For v = setjmp(buf), we generate
10372 //
10373 // thisMBB:
10374 // SjLjSetup mainMBB
10375 // bl mainMBB
10376 // v_restore = 1
10377 // b sinkMBB
10378 //
10379 // mainMBB:
10380 // buf[LabelOffset] = LR
10381 // v_main = 0
10382 //
10383 // sinkMBB:
10384 // v = phi(main, restore)
10385 //
10386
10387 MachineBasicBlock *thisMBB = MBB;
10388 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10389 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10390 MF->insert(I, mainMBB);
10391 MF->insert(I, sinkMBB);
10392
10393 MachineInstrBuilder MIB;
10394
10395 // Transfer the remainder of BB and its successor edges to sinkMBB.
10396 sinkMBB->splice(sinkMBB->begin(), MBB,
10397 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10398 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10399
10400 // Note that the structure of the jmp_buf used here is not compatible
10401 // with that used by libc, and is not designed to be. Specifically, it
10402 // stores only those 'reserved' registers that LLVM does not otherwise
10403 // understand how to spill. Also, by convention, by the time this
10404 // intrinsic is called, Clang has already stored the frame address in the
10405 // first slot of the buffer and stack address in the third. Following the
10406 // X86 target code, we'll store the jump address in the second slot. We also
10407 // need to save the TOC pointer (R2) to handle jumps between shared
10408 // libraries, and that will be stored in the fourth slot. The thread
10409 // identifier (R13) is not affected.
10410
10411 // thisMBB:
10412 const int64_t LabelOffset = 1 * PVT.getStoreSize();
10413 const int64_t TOCOffset = 3 * PVT.getStoreSize();
10414 const int64_t BPOffset = 4 * PVT.getStoreSize();
10415
10416 // Prepare IP either in reg.
10417 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10418 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
10419 unsigned BufReg = MI.getOperand(1).getReg();
10420
10421 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
10422 setUsesTOCBasePtr(*MBB->getParent());
10423 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10424 .addReg(PPC::X2)
10425 .addImm(TOCOffset)
10426 .addReg(BufReg)
10427 .cloneMemRefs(MI);
10428 }
10429
10430 // Naked functions never have a base pointer, and so we use r1. For all
10431 // other functions, this decision must be delayed until during PEI.
10432 unsigned BaseReg;
10433 if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10434 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10435 else
10436 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10437
10438 MIB = BuildMI(*thisMBB, MI, DL,
10439 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10440 .addReg(BaseReg)
10441 .addImm(BPOffset)
10442 .addReg(BufReg)
10443 .cloneMemRefs(MI);
10444
10445 // Setup
10446 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10447 MIB.addRegMask(TRI->getNoPreservedMask());
10448
10449 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10450
10451 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10452 .addMBB(mainMBB);
10453 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10454
10455 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10456 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10457
10458 // mainMBB:
10459 // mainDstReg = 0
10460 MIB =
10461 BuildMI(mainMBB, DL,
10462 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10463
10464 // Store IP
10465 if (Subtarget.isPPC64()) {
10466 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10467 .addReg(LabelReg)
10468 .addImm(LabelOffset)
10469 .addReg(BufReg);
10470 } else {
10471 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10472 .addReg(LabelReg)
10473 .addImm(LabelOffset)
10474 .addReg(BufReg);
10475 }
10476 MIB.cloneMemRefs(MI);
10477
10478 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10479 mainMBB->addSuccessor(sinkMBB);
10480
10481 // sinkMBB:
10482 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10483 TII->get(PPC::PHI), DstReg)
10484 .addReg(mainDstReg).addMBB(mainMBB)
10485 .addReg(restoreDstReg).addMBB(thisMBB);
10486
10487 MI.eraseFromParent();
10488 return sinkMBB;
10489}
10490
10491MachineBasicBlock *
10492PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10493 MachineBasicBlock *MBB) const {
10494 DebugLoc DL = MI.getDebugLoc();
10495 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10496
10497 MachineFunction *MF = MBB->getParent();
10498 MachineRegisterInfo &MRI = MF->getRegInfo();
10499
10500 MVT PVT = getPointerTy(MF->getDataLayout());
10501 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10502 "Invalid Pointer Size!");
10503
10504 const TargetRegisterClass *RC =
10505 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10506 unsigned Tmp = MRI.createVirtualRegister(RC);
10507 // Since FP is only updated here but NOT referenced, it's treated as GPR.
10508 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10509 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10510 unsigned BP =
10511 (PVT == MVT::i64)
10512 ? PPC::X30
10513 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10514 : PPC::R30);
10515
10516 MachineInstrBuilder MIB;
10517
10518 const int64_t LabelOffset = 1 * PVT.getStoreSize();
10519 const int64_t SPOffset = 2 * PVT.getStoreSize();
10520 const int64_t TOCOffset = 3 * PVT.getStoreSize();
10521 const int64_t BPOffset = 4 * PVT.getStoreSize();
10522
10523 unsigned BufReg = MI.getOperand(0).getReg();
10524
10525 // Reload FP (the jumped-to function may not have had a
10526 // frame pointer, and if so, then its r31 will be restored
10527 // as necessary).
10528 if (PVT == MVT::i64) {
10529 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10530 .addImm(0)
10531 .addReg(BufReg);
10532 } else {
10533 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10534 .addImm(0)
10535 .addReg(BufReg);
10536 }
10537 MIB.cloneMemRefs(MI);
10538
10539 // Reload IP
10540 if (PVT == MVT::i64) {
10541 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10542 .addImm(LabelOffset)
10543 .addReg(BufReg);
10544 } else {
10545 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10546 .addImm(LabelOffset)
10547 .addReg(BufReg);
10548 }
10549 MIB.cloneMemRefs(MI);
10550
10551 // Reload SP
10552 if (PVT == MVT::i64) {
10553 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10554 .addImm(SPOffset)
10555 .addReg(BufReg);
10556 } else {
10557 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10558 .addImm(SPOffset)
10559 .addReg(BufReg);
10560 }
10561 MIB.cloneMemRefs(MI);
10562
10563 // Reload BP
10564 if (PVT == MVT::i64) {
10565 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10566 .addImm(BPOffset)
10567 .addReg(BufReg);
10568 } else {
10569 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10570 .addImm(BPOffset)
10571 .addReg(BufReg);
10572 }
10573 MIB.cloneMemRefs(MI);
10574
10575 // Reload TOC
10576 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
10577 setUsesTOCBasePtr(*MBB->getParent());
10578 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
10579 .addImm(TOCOffset)
10580 .addReg(BufReg)
10581 .cloneMemRefs(MI);
10582 }
10583
10584 // Jump
10585 BuildMI(*MBB, MI, DL,
10586 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
10587 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
10588
10589 MI.eraseFromParent();
10590 return MBB;
10591}
10592
10593MachineBasicBlock *
10594PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10595 MachineBasicBlock *BB) const {
10596 if (MI.getOpcode() == TargetOpcode::STACKMAP ||
10597 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10598 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
10599 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10600 // Call lowering should have added an r2 operand to indicate a dependence
10601 // on the TOC base pointer value. It can't however, because there is no
10602 // way to mark the dependence as implicit there, and so the stackmap code
10603 // will confuse it with a regular operand. Instead, add the dependence
10604 // here.
10605 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10606 }
10607
10608 return emitPatchPoint(MI, BB);
10609 }
10610
10611 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10612 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10613 return emitEHSjLjSetJmp(MI, BB);
10614 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10615 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10616 return emitEHSjLjLongJmp(MI, BB);
10617 }
10618
10619 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10620
10621 // To "insert" these instructions we actually have to insert their
10622 // control-flow patterns.
10623 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10624 MachineFunction::iterator It = ++BB->getIterator();
10625
10626 MachineFunction *F = BB->getParent();
10627
10628 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10629 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
10630 MI.getOpcode() == PPC::SELECT_I8) {
10631 SmallVector<MachineOperand, 2> Cond;
10632 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10633 MI.getOpcode() == PPC::SELECT_CC_I8)
10634 Cond.push_back(MI.getOperand(4));
10635 else
10636 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10637 Cond.push_back(MI.getOperand(1));
10638
10639 DebugLoc dl = MI.getDebugLoc();
10640 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10641 MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10642 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10643 MI.getOpcode() == PPC::SELECT_CC_I8 ||
10644 MI.getOpcode() == PPC::SELECT_CC_F4 ||
10645 MI.getOpcode() == PPC::SELECT_CC_F8 ||
10646 MI.getOpcode() == PPC::SELECT_CC_F16 ||
10647 MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10648 MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10649 MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10650 MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10651 MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10652 MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10653 MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10654 MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
10655 MI.getOpcode() == PPC::SELECT_CC_SPE ||
10656 MI.getOpcode() == PPC::SELECT_I4 ||
10657 MI.getOpcode() == PPC::SELECT_I8 ||
10658 MI.getOpcode() == PPC::SELECT_F4 ||
10659 MI.getOpcode() == PPC::SELECT_F8 ||
10660 MI.getOpcode() == PPC::SELECT_F16 ||
10661 MI.getOpcode() == PPC::SELECT_QFRC ||
10662 MI.getOpcode() == PPC::SELECT_QSRC ||
10663 MI.getOpcode() == PPC::SELECT_QBRC ||
10664 MI.getOpcode() == PPC::SELECT_SPE ||
10665 MI.getOpcode() == PPC::SELECT_SPE4 ||
10666 MI.getOpcode() == PPC::SELECT_VRRC ||
10667 MI.getOpcode() == PPC::SELECT_VSFRC ||
10668 MI.getOpcode() == PPC::SELECT_VSSRC ||
10669 MI.getOpcode() == PPC::SELECT_VSRC) {
10670 // The incoming instruction knows the destination vreg to set, the
10671 // condition code register to branch on, the true/false values to
10672 // select between, and a branch opcode to use.
10673
10674 // thisMBB:
10675 // ...
10676 // TrueVal = ...
10677 // cmpTY ccX, r1, r2
10678 // bCC copy1MBB
10679 // fallthrough --> copy0MBB
10680 MachineBasicBlock *thisMBB = BB;
10681 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10682 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10683 DebugLoc dl = MI.getDebugLoc();
10684 F->insert(It, copy0MBB);
10685 F->insert(It, sinkMBB);
10686
10687 // Transfer the remainder of BB and its successor edges to sinkMBB.
10688 sinkMBB->splice(sinkMBB->begin(), BB,
10689 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10690 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10691
10692 // Next, add the true and fallthrough blocks as its successors.
10693 BB->addSuccessor(copy0MBB);
10694 BB->addSuccessor(sinkMBB);
10695
10696 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10697 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10698 MI.getOpcode() == PPC::SELECT_F16 ||
10699 MI.getOpcode() == PPC::SELECT_SPE4 ||
10700 MI.getOpcode() == PPC::SELECT_SPE ||
10701 MI.getOpcode() == PPC::SELECT_QFRC ||
10702 MI.getOpcode() == PPC::SELECT_QSRC ||
10703 MI.getOpcode() == PPC::SELECT_QBRC ||
10704 MI.getOpcode() == PPC::SELECT_VRRC ||
10705 MI.getOpcode() == PPC::SELECT_VSFRC ||
10706 MI.getOpcode() == PPC::SELECT_VSSRC ||
10707 MI.getOpcode() == PPC::SELECT_VSRC) {
10708 BuildMI(BB, dl, TII->get(PPC::BC))
10709 .addReg(MI.getOperand(1).getReg())
10710 .addMBB(sinkMBB);
10711 } else {
10712 unsigned SelectPred = MI.getOperand(4).getImm();
10713 BuildMI(BB, dl, TII->get(PPC::BCC))
10714 .addImm(SelectPred)
10715 .addReg(MI.getOperand(1).getReg())
10716 .addMBB(sinkMBB);
10717 }
10718
10719 // copy0MBB:
10720 // %FalseValue = ...
10721 // # fallthrough to sinkMBB
10722 BB = copy0MBB;
10723
10724 // Update machine-CFG edges
10725 BB->addSuccessor(sinkMBB);
10726
10727 // sinkMBB:
10728 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10729 // ...
10730 BB = sinkMBB;
10731 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10732 .addReg(MI.getOperand(3).getReg())
10733 .addMBB(copy0MBB)
10734 .addReg(MI.getOperand(2).getReg())
10735 .addMBB(thisMBB);
10736 } else if (MI.getOpcode() == PPC::ReadTB) {
10737 // To read the 64-bit time-base register on a 32-bit target, we read the
10738 // two halves. Should the counter have wrapped while it was being read, we
10739 // need to try again.
10740 // ...
10741 // readLoop:
10742 // mfspr Rx,TBU # load from TBU
10743 // mfspr Ry,TB # load from TB
10744 // mfspr Rz,TBU # load from TBU
10745 // cmpw crX,Rx,Rz # check if 'old'='new'
10746 // bne readLoop # branch if they're not equal
10747 // ...
10748
10749 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10750 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10751 DebugLoc dl = MI.getDebugLoc();
10752 F->insert(It, readMBB);
10753 F->insert(It, sinkMBB);
10754
10755 // Transfer the remainder of BB and its successor edges to sinkMBB.
10756 sinkMBB->splice(sinkMBB->begin(), BB,
10757 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10758 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10759
10760 BB->addSuccessor(readMBB);
10761 BB = readMBB;
10762
10763 MachineRegisterInfo &RegInfo = F->getRegInfo();
10764 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10765 unsigned LoReg = MI.getOperand(0).getReg();
10766 unsigned HiReg = MI.getOperand(1).getReg();
10767
10768 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10769 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10770 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10771
10772 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10773
10774 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10775 .addReg(HiReg)
10776 .addReg(ReadAgainReg);
10777 BuildMI(BB, dl, TII->get(PPC::BCC))
10778 .addImm(PPC::PRED_NE)
10779 .addReg(CmpReg)
10780 .addMBB(readMBB);
10781
10782 BB->addSuccessor(readMBB);
10783 BB->addSuccessor(sinkMBB);
10784 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10785 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10786 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10787 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10788 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10789 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10790 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10791 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10792
10793 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10794 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10795 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10796 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10797 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10798 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10799 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10800 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10801
10802 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10803 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10804 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10805 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10806 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10807 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10808 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10809 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10810
10811 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10812 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10813 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10814 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10815 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10816 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10817 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10818 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10819
10820 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10821 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10822 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10823 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10824 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10825 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10826 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10827 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10828
10829 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10830 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10831 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10832 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10833 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10834 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10835 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10836 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10837
10838 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10839 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10840 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10841 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10842 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10843 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10844 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10845 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10846
10847 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10848 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10849 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10850 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10851 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10852 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10853 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10854 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10855
10856 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10857 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10858 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10859 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10860 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10861 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10862 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10863 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10864
10865 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10866 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10867 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10868 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10869 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10870 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10871 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10872 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10873
10874 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10875 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10876 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10877 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10878 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10879 BB = EmitAtomicBinary(MI, BB, 4, 0);
10880 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10881 BB = EmitAtomicBinary(MI, BB, 8, 0);
10882 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10883 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10884 (Subtarget.hasPartwordAtomics() &&
10885 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10886 (Subtarget.hasPartwordAtomics() &&
10887 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10888 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10889
10890 auto LoadMnemonic = PPC::LDARX;
10891 auto StoreMnemonic = PPC::STDCX;
10892 switch (MI.getOpcode()) {
10893 default:
10894 llvm_unreachable("Compare and swap of unknown size");
10895 case PPC::ATOMIC_CMP_SWAP_I8:
10896 LoadMnemonic = PPC::LBARX;
10897 StoreMnemonic = PPC::STBCX;
10898 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10899 break;
10900 case PPC::ATOMIC_CMP_SWAP_I16:
10901 LoadMnemonic = PPC::LHARX;
10902 StoreMnemonic = PPC::STHCX;
10903 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10904 break;
10905 case PPC::ATOMIC_CMP_SWAP_I32:
10906 LoadMnemonic = PPC::LWARX;
10907 StoreMnemonic = PPC::STWCX;
10908 break;
10909 case PPC::ATOMIC_CMP_SWAP_I64:
10910 LoadMnemonic = PPC::LDARX;
10911 StoreMnemonic = PPC::STDCX;
10912 break;
10913 }
10914 unsigned dest = MI.getOperand(0).getReg();
10915 unsigned ptrA = MI.getOperand(1).getReg();
10916 unsigned ptrB = MI.getOperand(2).getReg();
10917 unsigned oldval = MI.getOperand(3).getReg();
10918 unsigned newval = MI.getOperand(4).getReg();
10919 DebugLoc dl = MI.getDebugLoc();
10920
10921 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10922 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10923 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10924 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10925 F->insert(It, loop1MBB);
10926 F->insert(It, loop2MBB);
10927 F->insert(It, midMBB);
10928 F->insert(It, exitMBB);
10929 exitMBB->splice(exitMBB->begin(), BB,
10930 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10931 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10932
10933 // thisMBB:
10934 // ...
10935 // fallthrough --> loopMBB
10936 BB->addSuccessor(loop1MBB);
10937
10938 // loop1MBB:
10939 // l[bhwd]arx dest, ptr
10940 // cmp[wd] dest, oldval
10941 // bne- midMBB
10942 // loop2MBB:
10943 // st[bhwd]cx. newval, ptr
10944 // bne- loopMBB
10945 // b exitBB
10946 // midMBB:
10947 // st[bhwd]cx. dest, ptr
10948 // exitBB:
10949 BB = loop1MBB;
10950 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
10951 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
10952 .addReg(oldval)
10953 .addReg(dest);
10954 BuildMI(BB, dl, TII->get(PPC::BCC))
10955 .addImm(PPC::PRED_NE)
10956 .addReg(PPC::CR0)
10957 .addMBB(midMBB);
10958 BB->addSuccessor(loop2MBB);
10959 BB->addSuccessor(midMBB);
10960
10961 BB = loop2MBB;
10962 BuildMI(BB, dl, TII->get(StoreMnemonic))
10963 .addReg(newval)
10964 .addReg(ptrA)
10965 .addReg(ptrB);
10966 BuildMI(BB, dl, TII->get(PPC::BCC))
10967 .addImm(PPC::PRED_NE)
10968 .addReg(PPC::CR0)
10969 .addMBB(loop1MBB);
10970 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10971 BB->addSuccessor(loop1MBB);
10972 BB->addSuccessor(exitMBB);
10973
10974 BB = midMBB;
10975 BuildMI(BB, dl, TII->get(StoreMnemonic))
10976 .addReg(dest)
10977 .addReg(ptrA)
10978 .addReg(ptrB);
10979 BB->addSuccessor(exitMBB);
10980
10981 // exitMBB:
10982 // ...
10983 BB = exitMBB;
10984 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
10985 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
10986 // We must use 64-bit registers for addresses when targeting 64-bit,
10987 // since we're actually doing arithmetic on them. Other registers
10988 // can be 32-bit.
10989 bool is64bit = Subtarget.isPPC64();
10990 bool isLittleEndian = Subtarget.isLittleEndian();
10991 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
10992
10993 unsigned dest = MI.getOperand(0).getReg();
10994 unsigned ptrA = MI.getOperand(1).getReg();
10995 unsigned ptrB = MI.getOperand(2).getReg();
10996 unsigned oldval = MI.getOperand(3).getReg();
10997 unsigned newval = MI.getOperand(4).getReg();
10998 DebugLoc dl = MI.getDebugLoc();
10999
11000 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11001 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11002 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11003 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11004 F->insert(It, loop1MBB);
11005 F->insert(It, loop2MBB);
11006 F->insert(It, midMBB);
11007 F->insert(It, exitMBB);
11008 exitMBB->splice(exitMBB->begin(), BB,
11009 std::next(MachineBasicBlock::iterator(MI)), BB->end());
11010 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11011
11012 MachineRegisterInfo &RegInfo = F->getRegInfo();
11013 const TargetRegisterClass *RC =
11014 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11015 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11016
11017 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
11018 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11019 unsigned ShiftReg =
11020 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11021 unsigned NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11022 unsigned NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11023 unsigned OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11024 unsigned OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11025 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC);
11026 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11027 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11028 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11029 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11030 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11031 unsigned Ptr1Reg;
11032 unsigned TmpReg = RegInfo.createVirtualRegister(GPRC);
11033 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11034 // thisMBB:
11035 // ...
11036 // fallthrough --> loopMBB
11037 BB->addSuccessor(loop1MBB);
11038
11039 // The 4-byte load must be aligned, while a char or short may be
11040 // anywhere in the word. Hence all this nasty bookkeeping code.
11041 // add ptr1, ptrA, ptrB [copy if ptrA==0]
11042 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11043 // xori shift, shift1, 24 [16]
11044 // rlwinm ptr, ptr1, 0, 0, 29
11045 // slw newval2, newval, shift
11046 // slw oldval2, oldval,shift
11047 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11048 // slw mask, mask2, shift
11049 // and newval3, newval2, mask
11050 // and oldval3, oldval2, mask
11051 // loop1MBB:
11052 // lwarx tmpDest, ptr
11053 // and tmp, tmpDest, mask
11054 // cmpw tmp, oldval3
11055 // bne- midMBB
11056 // loop2MBB:
11057 // andc tmp2, tmpDest, mask
11058 // or tmp4, tmp2, newval3
11059 // stwcx. tmp4, ptr
11060 // bne- loop1MBB
11061 // b exitBB
11062 // midMBB:
11063 // stwcx. tmpDest, ptr
11064 // exitBB:
11065 // srw dest, tmpDest, shift
11066 if (ptrA != ZeroReg) {
11067 Ptr1Reg = RegInfo.createVirtualRegister(RC);
11068 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11069 .addReg(ptrA)
11070 .addReg(ptrB);
11071 } else {
11072 Ptr1Reg = ptrB;
11073 }
11074
11075 // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11076 // mode.
11077 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11078 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11079 .addImm(3)
11080 .addImm(27)
11081 .addImm(is8bit ? 28 : 27);
11082 if (!isLittleEndian)
11083 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11084 .addReg(Shift1Reg)
11085 .addImm(is8bit ? 24 : 16);
11086 if (is64bit)
11087 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11088 .addReg(Ptr1Reg)
11089 .addImm(0)
11090 .addImm(61);
11091 else
11092 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11093 .addReg(Ptr1Reg)
11094 .addImm(0)
11095 .addImm(0)
11096 .addImm(29);
11097 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11098 .addReg(newval)
11099 .addReg(ShiftReg);
11100 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11101 .addReg(oldval)
11102 .addReg(ShiftReg);
11103 if (is8bit)
11104 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11105 else {
11106 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11107 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11108 .addReg(Mask3Reg)
11109 .addImm(65535);
11110 }
11111 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11112 .addReg(Mask2Reg)
11113 .addReg(ShiftReg);
11114 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11115 .addReg(NewVal2Reg)
11116 .addReg(MaskReg);
11117 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11118 .addReg(OldVal2Reg)
11119 .addReg(MaskReg);
11120
11121 BB = loop1MBB;
11122 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11123 .addReg(ZeroReg)
11124 .addReg(PtrReg);
11125 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11126 .addReg(TmpDestReg)
11127 .addReg(MaskReg);
11128 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11129 .addReg(TmpReg)
11130 .addReg(OldVal3Reg);
11131 BuildMI(BB, dl, TII->get(PPC::BCC))
11132 .addImm(PPC::PRED_NE)
11133 .addReg(PPC::CR0)
11134 .addMBB(midMBB);
11135 BB->addSuccessor(loop2MBB);
11136 BB->addSuccessor(midMBB);
11137
11138 BB = loop2MBB;
11139 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11140 .addReg(TmpDestReg)
11141 .addReg(MaskReg);
11142 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11143 .addReg(Tmp2Reg)
11144 .addReg(NewVal3Reg);
11145 BuildMI(BB, dl, TII->get(PPC::STWCX))
11146 .addReg(Tmp4Reg)
11147 .addReg(ZeroReg)
11148 .addReg(PtrReg);
11149 BuildMI(BB, dl, TII->get(PPC::BCC))
11150 .addImm(PPC::PRED_NE)
11151 .addReg(PPC::CR0)
11152 .addMBB(loop1MBB);
11153 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11154 BB->addSuccessor(loop1MBB);
11155 BB->addSuccessor(exitMBB);
11156
11157 BB = midMBB;
11158 BuildMI(BB, dl, TII->get(PPC::STWCX))
11159 .addReg(TmpDestReg)
11160 .addReg(ZeroReg)
11161 .addReg(PtrReg);
11162 BB->addSuccessor(exitMBB);
11163
11164 // exitMBB:
11165 // ...
11166 BB = exitMBB;
11167 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11168 .addReg(TmpReg)
11169 .addReg(ShiftReg);
11170 } else if (MI.getOpcode() == PPC::FADDrtz) {
11171 // This pseudo performs an FADD with rounding mode temporarily forced
11172 // to round-to-zero. We emit this via custom inserter since the FPSCR
11173 // is not modeled at the SelectionDAG level.
11174 unsigned Dest = MI.getOperand(0).getReg();
11175 unsigned Src1 = MI.getOperand(1).getReg();
11176 unsigned Src2 = MI.getOperand(2).getReg();
11177 DebugLoc dl = MI.getDebugLoc();
11178
11179 MachineRegisterInfo &RegInfo = F->getRegInfo();
11180 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11181
11182 // Save FPSCR value.
11183 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11184
11185 // Set rounding mode to round-to-zero.
11186 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11187 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11188
11189 // Perform addition.
11190 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11191
11192 // Restore FPSCR value.
11193 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11194 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11195 MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
11196 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11197 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
11198 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11199 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
11200 ? PPC::ANDIo8
11201 : PPC::ANDIo;
11202 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11203 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
11204
11205 MachineRegisterInfo &RegInfo = F->getRegInfo();
11206 unsigned Dest = RegInfo.createVirtualRegister(
11207 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11208
11209 DebugLoc dl = MI.getDebugLoc();
11210 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
11211 .addReg(MI.getOperand(1).getReg())
11212 .addImm(1);
11213 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
11214 MI.getOperand(0).getReg())
11215 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
11216 } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11217 DebugLoc Dl = MI.getDebugLoc();
11218 MachineRegisterInfo &RegInfo = F->getRegInfo();
11219 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11220 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11221 return BB;
11222 } else if (MI.getOpcode() == PPC::SETRNDi) {
11223 DebugLoc dl = MI.getDebugLoc();
11224 unsigned OldFPSCRReg = MI.getOperand(0).getReg();
11225
11226 // Save FPSCR value.
11227 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11228
11229 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11230 // the following settings:
11231 // 00 Round to nearest
11232 // 01 Round to 0
11233 // 10 Round to +inf
11234 // 11 Round to -inf
11235
11236 // When the operand is immediate, using the two least significant bits of
11237 // the immediate to set the bits 62:63 of FPSCR.
11238 unsigned Mode = MI.getOperand(1).getImm();
11239 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11240 .addImm(31);
11241
11242 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11243 .addImm(30);
11244 } else if (MI.getOpcode() == PPC::SETRND) {
11245 DebugLoc dl = MI.getDebugLoc();
11246
11247 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11248 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11249 // If the target doesn't have DirectMove, we should use stack to do the
11250 // conversion, because the target doesn't have the instructions like mtvsrd
11251 // or mfvsrd to do this conversion directly.
11252 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11253 if (Subtarget.hasDirectMove()) {
11254 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11255 .addReg(SrcReg);
11256 } else {
11257 // Use stack to do the register copy.
11258 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11259 MachineRegisterInfo &RegInfo = F->getRegInfo();
11260 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11261 if (RC == &PPC::F8RCRegClass) {
11262 // Copy register from F8RCRegClass to G8RCRegclass.
11263 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11264 "Unsupported RegClass.");
11265
11266 StoreOp = PPC::STFD;
11267 LoadOp = PPC::LD;
11268 } else {
11269 // Copy register from G8RCRegClass to F8RCRegclass.
11270 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11271 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11272 "Unsupported RegClass.");
11273 }
11274
11275 MachineFrameInfo &MFI = F->getFrameInfo();
11276 int FrameIdx = MFI.CreateStackObject(8, 8, false);
11277
11278 MachineMemOperand *MMOStore = F->getMachineMemOperand(
11279 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11280 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11281 MFI.getObjectAlignment(FrameIdx));
11282
11283 // Store the SrcReg into the stack.
11284 BuildMI(*BB, MI, dl, TII->get(StoreOp))
11285 .addReg(SrcReg)
11286 .addImm(0)
11287 .addFrameIndex(FrameIdx)
11288 .addMemOperand(MMOStore);
11289
11290 MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11291 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11292 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11293 MFI.getObjectAlignment(FrameIdx));
11294
11295 // Load from the stack where SrcReg is stored, and save to DestReg,
11296 // so we have done the RegClass conversion from RegClass::SrcReg to
11297 // RegClass::DestReg.
11298 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11299 .addImm(0)
11300 .addFrameIndex(FrameIdx)
11301 .addMemOperand(MMOLoad);
11302 }
11303 };
11304
11305 unsigned OldFPSCRReg = MI.getOperand(0).getReg();
11306
11307 // Save FPSCR value.
11308 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11309
11310 // When the operand is gprc register, use two least significant bits of the
11311 // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11312 //
11313 // copy OldFPSCRTmpReg, OldFPSCRReg
11314 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11315 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11316 // copy NewFPSCRReg, NewFPSCRTmpReg
11317 // mtfsf 255, NewFPSCRReg
11318 MachineOperand SrcOp = MI.getOperand(1);
11319 MachineRegisterInfo &RegInfo = F->getRegInfo();
11320 unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11321
11322 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11323
11324 unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11325 unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11326
11327 // The first operand of INSERT_SUBREG should be a register which has
11328 // subregisters, we only care about its RegClass, so we should use an
11329 // IMPLICIT_DEF register.
11330 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11331 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11332 .addReg(ImDefReg)
11333 .add(SrcOp)
11334 .addImm(1);
11335
11336 unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11337 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11338 .addReg(OldFPSCRTmpReg)
11339 .addReg(ExtSrcReg)
11340 .addImm(0)
11341 .addImm(62);
11342
11343 unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11344 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11345
11346 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11347 // bits of FPSCR.
11348 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11349 .addImm(255)
11350 .addReg(NewFPSCRReg)
11351 .addImm(0)
11352 .addImm(0);
11353 } else {
11354 llvm_unreachable("Unexpected instr type to insert");
11355 }
11356
11357 MI.eraseFromParent(); // The pseudo instruction is gone now.
11358 return BB;
11359}
11360
11361//===----------------------------------------------------------------------===//
11362// Target Optimization Hooks
11363//===----------------------------------------------------------------------===//
11364
11365static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11366 // For the estimates, convergence is quadratic, so we essentially double the
11367 // number of digits correct after every iteration. For both FRE and FRSQRTE,
11368 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11369 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11370 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11371 if (VT.getScalarType() == MVT::f64)
11372 RefinementSteps++;
11373 return RefinementSteps;
11374}
11375
11376SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11377 int Enabled, int &RefinementSteps,
11378 bool &UseOneConstNR,
11379 bool Reciprocal) const {
11380 EVT VT = Operand.getValueType();
11381 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11382 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11383 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11384 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11385 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11386 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11387 if (RefinementSteps == ReciprocalEstimate::Unspecified)
11388 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11389
11390 // The Newton-Raphson computation with a single constant does not provide
11391 // enough accuracy on some CPUs.
11392 UseOneConstNR = !Subtarget.needsTwoConstNR();
11393 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11394 }
11395 return SDValue();
11396}
11397
11398SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11399 int Enabled,
11400 int &RefinementSteps) const {
11401 EVT VT = Operand.getValueType();
11402 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11403 (VT == MVT::f64 && Subtarget.hasFRE()) ||
11404 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11405 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11406 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11407 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11408 if (RefinementSteps == ReciprocalEstimate::Unspecified)
11409 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11410 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11411 }
11412 return SDValue();
11413}
11414
11415unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11416 // Note: This functionality is used only when unsafe-fp-math is enabled, and
11417 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11418 // enabled for division), this functionality is redundant with the default
11419 // combiner logic (once the division -> reciprocal/multiply transformation
11420 // has taken place). As a result, this matters more for older cores than for
11421 // newer ones.
11422
11423 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11424 // reciprocal if there are two or more FDIVs (for embedded cores with only
11425 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11426 switch (Subtarget.getDarwinDirective()) {
11427 default:
11428 return 3;
11429 case PPC::DIR_440:
11430 case PPC::DIR_A2:
11431 case PPC::DIR_E500:
11432 case PPC::DIR_E500mc:
11433 case PPC::DIR_E5500:
11434 return 2;
11435 }
11436}
11437
11438// isConsecutiveLSLoc needs to work even if all adds have not yet been
11439// collapsed, and so we need to look through chains of them.
11440static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11441 int64_t& Offset, SelectionDAG &DAG) {
11442 if (DAG.isBaseWithConstantOffset(Loc)) {
11443 Base = Loc.getOperand(0);
11444 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11445
11446 // The base might itself be a base plus an offset, and if so, accumulate
11447 // that as well.
11448 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11449 }
11450}
11451
11452static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11453 unsigned Bytes, int Dist,
11454 SelectionDAG &DAG) {
11455 if (VT.getSizeInBits() / 8 != Bytes)
11456 return false;
11457
11458 SDValue BaseLoc = Base->getBasePtr();
11459 if (Loc.getOpcode() == ISD::FrameIndex) {
11460 if (BaseLoc.getOpcode() != ISD::FrameIndex)
11461 return false;
11462 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11463 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
11464 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11465 int FS = MFI.getObjectSize(FI);
11466 int BFS = MFI.getObjectSize(BFI);
11467 if (FS != BFS || FS != (int)Bytes) return false;
11468 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11469 }
11470
11471 SDValue Base1 = Loc, Base2 = BaseLoc;
11472 int64_t Offset1 = 0, Offset2 = 0;
11473 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
11474 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
11475 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
11476 return true;
11477
11478 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11479 const GlobalValue *GV1 = nullptr;
11480 const GlobalValue *GV2 = nullptr;
11481 Offset1 = 0;
11482 Offset2 = 0;
11483 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
11484 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
11485 if (isGA1 && isGA2 && GV1 == GV2)
11486 return Offset1 == (Offset2 + Dist*Bytes);
11487 return false;
11488}
11489
11490// Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
11491// not enforce equality of the chain operands.
11492static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
11493 unsigned Bytes, int Dist,
11494 SelectionDAG &DAG) {
11495 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
11496 EVT VT = LS->getMemoryVT();
11497 SDValue Loc = LS->getBasePtr();
11498 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
11499 }
11500
11501 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
11502 EVT VT;
11503 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11504 default: return false;
11505 case Intrinsic::ppc_qpx_qvlfd:
11506 case Intrinsic::ppc_qpx_qvlfda:
11507 VT = MVT::v4f64;
11508 break;
11509 case Intrinsic::ppc_qpx_qvlfs:
11510 case Intrinsic::ppc_qpx_qvlfsa:
11511 VT = MVT::v4f32;
11512 break;
11513 case Intrinsic::ppc_qpx_qvlfcd:
11514 case Intrinsic::ppc_qpx_qvlfcda:
11515 VT = MVT::v2f64;
11516 break;
11517 case Intrinsic::ppc_qpx_qvlfcs:
11518 case Intrinsic::ppc_qpx_qvlfcsa:
11519 VT = MVT::v2f32;
11520 break;
11521 case Intrinsic::ppc_qpx_qvlfiwa:
11522 case Intrinsic::ppc_qpx_qvlfiwz:
11523 case Intrinsic::ppc_altivec_lvx:
11524 case Intrinsic::ppc_altivec_lvxl:
11525 case Intrinsic::ppc_vsx_lxvw4x:
11526 case Intrinsic::ppc_vsx_lxvw4x_be:
11527 VT = MVT::v4i32;
11528 break;
11529 case Intrinsic::ppc_vsx_lxvd2x:
11530 case Intrinsic::ppc_vsx_lxvd2x_be:
11531 VT = MVT::v2f64;
11532 break;
11533 case Intrinsic::ppc_altivec_lvebx:
11534 VT = MVT::i8;
11535 break;
11536 case Intrinsic::ppc_altivec_lvehx:
11537 VT = MVT::i16;
11538 break;
11539 case Intrinsic::ppc_altivec_lvewx:
11540 VT = MVT::i32;
11541 break;
11542 }
11543
11544 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
11545 }
11546
11547 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
11548 EVT VT;
11549 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11550 default: return false;
11551 case Intrinsic::ppc_qpx_qvstfd:
11552 case Intrinsic::ppc_qpx_qvstfda:
11553 VT = MVT::v4f64;
11554 break;
11555 case Intrinsic::ppc_qpx_qvstfs:
11556 case Intrinsic::ppc_qpx_qvstfsa:
11557 VT = MVT::v4f32;
11558 break;
11559 case Intrinsic::ppc_qpx_qvstfcd:
11560 case Intrinsic::ppc_qpx_qvstfcda:
11561 VT = MVT::v2f64;
11562 break;
11563 case Intrinsic::ppc_qpx_qvstfcs:
11564 case Intrinsic::ppc_qpx_qvstfcsa:
11565 VT = MVT::v2f32;
11566 break;
11567 case Intrinsic::ppc_qpx_qvstfiw:
11568 case Intrinsic::ppc_qpx_qvstfiwa:
11569 case Intrinsic::ppc_altivec_stvx:
11570 case Intrinsic::ppc_altivec_stvxl:
11571 case Intrinsic::ppc_vsx_stxvw4x:
11572 VT = MVT::v4i32;
11573 break;
11574 case Intrinsic::ppc_vsx_stxvd2x:
11575 VT = MVT::v2f64;
11576 break;
11577 case Intrinsic::ppc_vsx_stxvw4x_be:
11578 VT = MVT::v4i32;
11579 break;
11580 case Intrinsic::ppc_vsx_stxvd2x_be:
11581 VT = MVT::v2f64;
11582 break;
11583 case Intrinsic::ppc_altivec_stvebx:
11584 VT = MVT::i8;
11585 break;
11586 case Intrinsic::ppc_altivec_stvehx:
11587 VT = MVT::i16;
11588 break;
11589 case Intrinsic::ppc_altivec_stvewx:
11590 VT = MVT::i32;
11591 break;
11592 }
11593
11594 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
11595 }
11596
11597 return false;
11598}
11599
11600// Return true is there is a nearyby consecutive load to the one provided
11601// (regardless of alignment). We search up and down the chain, looking though
11602// token factors and other loads (but nothing else). As a result, a true result
11603// indicates that it is safe to create a new consecutive load adjacent to the
11604// load provided.
11605static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
11606 SDValue Chain = LD->getChain();
11607 EVT VT = LD->getMemoryVT();
11608
11609 SmallSet<SDNode *, 16> LoadRoots;
11610 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
11611 SmallSet<SDNode *, 16> Visited;
11612
11613 // First, search up the chain, branching to follow all token-factor operands.
11614 // If we find a consecutive load, then we're done, otherwise, record all
11615 // nodes just above the top-level loads and token factors.
11616 while (!Queue.empty()) {
11617 SDNode *ChainNext = Queue.pop_back_val();
11618 if (!Visited.insert(ChainNext).second)
11619 continue;
11620
11621 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
11622 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11623 return true;
11624
11625 if (!Visited.count(ChainLD->getChain().getNode()))
11626 Queue.push_back(ChainLD->getChain().getNode());
11627 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
11628 for (const SDUse &O : ChainNext->ops())
11629 if (!Visited.count(O.getNode()))
11630 Queue.push_back(O.getNode());
11631 } else
11632 LoadRoots.insert(ChainNext);
11633 }
11634
11635 // Second, search down the chain, starting from the top-level nodes recorded
11636 // in the first phase. These top-level nodes are the nodes just above all
11637 // loads and token factors. Starting with their uses, recursively look though
11638 // all loads (just the chain uses) and token factors to find a consecutive
11639 // load.
11640 Visited.clear();
11641 Queue.clear();
11642
11643 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
11644 IE = LoadRoots.end(); I != IE; ++I) {
11645 Queue.push_back(*I);
11646
11647 while (!Queue.empty()) {
11648 SDNode *LoadRoot = Queue.pop_back_val();
11649 if (!Visited.insert(LoadRoot).second)
11650 continue;
11651
11652 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
11653 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
11654 return true;
11655
11656 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
11657 UE = LoadRoot->use_end(); UI != UE; ++UI)
11658 if (((isa<MemSDNode>(*UI) &&
11659 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
11660 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
11661 Queue.push_back(*UI);
11662 }
11663 }
11664
11665 return false;
11666}
11667
11668/// This function is called when we have proved that a SETCC node can be replaced
11669/// by subtraction (and other supporting instructions) so that the result of
11670/// comparison is kept in a GPR instead of CR. This function is purely for
11671/// codegen purposes and has some flags to guide the codegen process.
11672static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
11673 bool Swap, SDLoc &DL, SelectionDAG &DAG) {
11674 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11675
11676 // Zero extend the operands to the largest legal integer. Originally, they
11677 // must be of a strictly smaller size.
11678 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
11679 DAG.getConstant(Size, DL, MVT::i32));
11680 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
11681 DAG.getConstant(Size, DL, MVT::i32));
11682
11683 // Swap if needed. Depends on the condition code.
11684 if (Swap)
11685 std::swap(Op0, Op1);
11686
11687 // Subtract extended integers.
11688 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
11689
11690 // Move the sign bit to the least significant position and zero out the rest.
11691 // Now the least significant bit carries the result of original comparison.
11692 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
11693 DAG.getConstant(Size - 1, DL, MVT::i32));
11694 auto Final = Shifted;
11695
11696 // Complement the result if needed. Based on the condition code.
11697 if (Complement)
11698 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
11699 DAG.getConstant(1, DL, MVT::i64));
11700
11701 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
11702}
11703
11704SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
11705 DAGCombinerInfo &DCI) const {
11706 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11707
11708 SelectionDAG &DAG = DCI.DAG;
11709 SDLoc DL(N);
11710
11711 // Size of integers being compared has a critical role in the following
11712 // analysis, so we prefer to do this when all types are legal.
11713 if (!DCI.isAfterLegalizeDAG())
11714 return SDValue();
11715
11716 // If all users of SETCC extend its value to a legal integer type
11717 // then we replace SETCC with a subtraction
11718 for (SDNode::use_iterator UI = N->use_begin(),
11719 UE = N->use_end(); UI != UE; ++UI) {
11720 if (UI->getOpcode() != ISD::ZERO_EXTEND)
11721 return SDValue();
11722 }
11723
11724 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11725 auto OpSize = N->getOperand(0).getValueSizeInBits();
11726
11727 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
11728
11729 if (OpSize < Size) {
11730 switch (CC) {
11731 default: break;
11732 case ISD::SETULT:
11733 return generateEquivalentSub(N, Size, false, false, DL, DAG);
11734 case ISD::SETULE:
11735 return generateEquivalentSub(N, Size, true, true, DL, DAG);
11736 case ISD::SETUGT:
11737 return generateEquivalentSub(N, Size, false, true, DL, DAG);
11738 case ISD::SETUGE:
11739 return generateEquivalentSub(N, Size, true, false, DL, DAG);
11740 }
11741 }
11742
11743 return SDValue();
11744}
11745
11746SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
11747 DAGCombinerInfo &DCI) const {
11748 SelectionDAG &DAG = DCI.DAG;
11749 SDLoc dl(N);
11750
11751 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
11752 // If we're tracking CR bits, we need to be careful that we don't have:
11753 // trunc(binary-ops(zext(x), zext(y)))
11754 // or
11755 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
11756 // such that we're unnecessarily moving things into GPRs when it would be
11757 // better to keep them in CR bits.
11758
11759 // Note that trunc here can be an actual i1 trunc, or can be the effective
11760 // truncation that comes from a setcc or select_cc.
11761 if (N->getOpcode() == ISD::TRUNCATE &&
11762 N->getValueType(0) != MVT::i1)
11763 return SDValue();
11764
11765 if (N->getOperand(0).getValueType() != MVT::i32 &&
11766 N->getOperand(0).getValueType() != MVT::i64)
11767 return SDValue();
11768
11769 if (N->getOpcode() == ISD::SETCC ||
11770 N->getOpcode() == ISD::SELECT_CC) {
11771 // If we're looking at a comparison, then we need to make sure that the
11772 // high bits (all except for the first) don't matter the result.
11773 ISD::CondCode CC =
11774 cast<CondCodeSDNode>(N->getOperand(
11775 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
11776 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
11777
11778 if (ISD::isSignedIntSetCC(CC)) {
11779 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
11780 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
11781 return SDValue();
11782 } else if (ISD::isUnsignedIntSetCC(CC)) {
11783 if (!DAG.MaskedValueIsZero(N->getOperand(0),
11784 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
11785 !DAG.MaskedValueIsZero(N->getOperand(1),
11786 APInt::getHighBitsSet(OpBits, OpBits-1)))
11787 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
11788 : SDValue());
11789 } else {
11790 // This is neither a signed nor an unsigned comparison, just make sure
11791 // that the high bits are equal.
11792 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
11793 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
11794
11795 // We don't really care about what is known about the first bit (if
11796 // anything), so clear it in all masks prior to comparing them.
11797 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
11798 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
11799
11800 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
11801 return SDValue();
11802 }
11803 }
11804
11805 // We now know that the higher-order bits are irrelevant, we just need to
11806 // make sure that all of the intermediate operations are bit operations, and
11807 // all inputs are extensions.
11808 if (N->getOperand(0).getOpcode() != ISD::AND &&
11809 N->getOperand(0).getOpcode() != ISD::OR &&
11810 N->getOperand(0).getOpcode() != ISD::XOR &&
11811 N->getOperand(0).getOpcode() != ISD::SELECT &&
11812 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
11813 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
11814 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
11815 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
11816 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
11817 return SDValue();
11818
11819 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
11820 N->getOperand(1).getOpcode() != ISD::AND &&
11821 N->getOperand(1).getOpcode() != ISD::OR &&
11822 N->getOperand(1).getOpcode() != ISD::XOR &&
11823 N->getOperand(1).getOpcode() != ISD::SELECT &&
11824 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
11825 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
11826 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
11827 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
11828 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
11829 return SDValue();
11830
11831 SmallVector<SDValue, 4> Inputs;
11832 SmallVector<SDValue, 8> BinOps, PromOps;
11833 SmallPtrSet<SDNode *, 16> Visited;
11834
11835 for (unsigned i = 0; i < 2; ++i) {
11836 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11837 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11838 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11839 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11840 isa<ConstantSDNode>(N->getOperand(i)))
11841 Inputs.push_back(N->getOperand(i));
11842 else
11843 BinOps.push_back(N->getOperand(i));
11844
11845 if (N->getOpcode() == ISD::TRUNCATE)
11846 break;
11847 }
11848
11849 // Visit all inputs, collect all binary operations (and, or, xor and
11850 // select) that are all fed by extensions.
11851 while (!BinOps.empty()) {
11852 SDValue BinOp = BinOps.back();
11853 BinOps.pop_back();
11854
11855 if (!Visited.insert(BinOp.getNode()).second)
11856 continue;
11857
11858 PromOps.push_back(BinOp);
11859
11860 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11861 // The condition of the select is not promoted.
11862 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11863 continue;
11864 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11865 continue;
11866
11867 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11868 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11869 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11870 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11871 isa<ConstantSDNode>(BinOp.getOperand(i))) {
11872 Inputs.push_back(BinOp.getOperand(i));
11873 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11874 BinOp.getOperand(i).getOpcode() == ISD::OR ||
11875 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11876 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11877 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11878 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11879 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11880 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11881 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11882 BinOps.push_back(BinOp.getOperand(i));
11883 } else {
11884 // We have an input that is not an extension or another binary
11885 // operation; we'll abort this transformation.
11886 return SDValue();
11887 }
11888 }
11889 }
11890
11891 // Make sure that this is a self-contained cluster of operations (which
11892 // is not quite the same thing as saying that everything has only one
11893 // use).
11894 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11895 if (isa<ConstantSDNode>(Inputs[i]))
11896 continue;
11897
11898 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11899 UE = Inputs[i].getNode()->use_end();
11900 UI != UE; ++UI) {
11901 SDNode *User = *UI;
11902 if (User != N && !Visited.count(User))
11903 return SDValue();
11904
11905 // Make sure that we're not going to promote the non-output-value
11906 // operand(s) or SELECT or SELECT_CC.
11907 // FIXME: Although we could sometimes handle this, and it does occur in
11908 // practice that one of the condition inputs to the select is also one of
11909 // the outputs, we currently can't deal with this.
11910 if (User->getOpcode() == ISD::SELECT) {
11911 if (User->getOperand(0) == Inputs[i])
11912 return SDValue();
11913 } else if (User->getOpcode() == ISD::SELECT_CC) {
11914 if (User->getOperand(0) == Inputs[i] ||
11915 User->getOperand(1) == Inputs[i])
11916 return SDValue();
11917 }
11918 }
11919 }
11920
11921 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11922 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11923 UE = PromOps[i].getNode()->use_end();
11924 UI != UE; ++UI) {
11925 SDNode *User = *UI;
11926 if (User != N && !Visited.count(User))
11927 return SDValue();
11928
11929 // Make sure that we're not going to promote the non-output-value
11930 // operand(s) or SELECT or SELECT_CC.
11931 // FIXME: Although we could sometimes handle this, and it does occur in
11932 // practice that one of the condition inputs to the select is also one of
11933 // the outputs, we currently can't deal with this.
11934 if (User->getOpcode() == ISD::SELECT) {
11935 if (User->getOperand(0) == PromOps[i])
11936 return SDValue();
11937 } else if (User->getOpcode() == ISD::SELECT_CC) {
11938 if (User->getOperand(0) == PromOps[i] ||
11939 User->getOperand(1) == PromOps[i])
11940 return SDValue();
11941 }
11942 }
11943 }
11944
11945 // Replace all inputs with the extension operand.
11946 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11947 // Constants may have users outside the cluster of to-be-promoted nodes,
11948 // and so we need to replace those as we do the promotions.
11949 if (isa<ConstantSDNode>(Inputs[i]))
11950 continue;
11951 else
11952 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
11953 }
11954
11955 std::list<HandleSDNode> PromOpHandles;
11956 for (auto &PromOp : PromOps)
11957 PromOpHandles.emplace_back(PromOp);
11958
11959 // Replace all operations (these are all the same, but have a different
11960 // (i1) return type). DAG.getNode will validate that the types of
11961 // a binary operator match, so go through the list in reverse so that
11962 // we've likely promoted both operands first. Any intermediate truncations or
11963 // extensions disappear.
11964 while (!PromOpHandles.empty()) {
11965 SDValue PromOp = PromOpHandles.back().getValue();
11966 PromOpHandles.pop_back();
11967
11968 if (PromOp.getOpcode() == ISD::TRUNCATE ||
11969 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
11970 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
11971 PromOp.getOpcode() == ISD::ANY_EXTEND) {
11972 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
11973 PromOp.getOperand(0).getValueType() != MVT::i1) {
11974 // The operand is not yet ready (see comment below).
11975 PromOpHandles.emplace_front(PromOp);
11976 continue;
11977 }
11978
11979 SDValue RepValue = PromOp.getOperand(0);
11980 if (isa<ConstantSDNode>(RepValue))
11981 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
11982
11983 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
11984 continue;
11985 }
11986
11987 unsigned C;
11988 switch (PromOp.getOpcode()) {
11989 default: C = 0; break;
11990 case ISD::SELECT: C = 1; break;
11991 case ISD::SELECT_CC: C = 2; break;
11992 }
11993
11994 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11995 PromOp.getOperand(C).getValueType() != MVT::i1) ||
11996 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11997 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
11998 // The to-be-promoted operands of this node have not yet been
11999 // promoted (this should be rare because we're going through the
12000 // list backward, but if one of the operands has several users in
12001 // this cluster of to-be-promoted nodes, it is possible).
12002 PromOpHandles.emplace_front(PromOp);
12003 continue;
12004 }
12005
12006 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12007 PromOp.getNode()->op_end());
12008
12009 // If there are any constant inputs, make sure they're replaced now.
12010 for (unsigned i = 0; i < 2; ++i)
12011 if (isa<ConstantSDNode>(Ops[C+i]))
12012 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12013
12014 DAG.ReplaceAllUsesOfValueWith(PromOp,
12015 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12016 }
12017
12018 // Now we're left with the initial truncation itself.
12019 if (N->getOpcode() == ISD::TRUNCATE)
12020 return N->getOperand(0);
12021
12022 // Otherwise, this is a comparison. The operands to be compared have just
12023 // changed type (to i1), but everything else is the same.
12024 return SDValue(N, 0);
12025}
12026
12027SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12028 DAGCombinerInfo &DCI) const {
12029 SelectionDAG &DAG = DCI.DAG;
12030 SDLoc dl(N);
12031
12032 // If we're tracking CR bits, we need to be careful that we don't have:
12033 // zext(binary-ops(trunc(x), trunc(y)))
12034 // or
12035 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12036 // such that we're unnecessarily moving things into CR bits that can more
12037 // efficiently stay in GPRs. Note that if we're not certain that the high
12038 // bits are set as required by the final extension, we still may need to do
12039 // some masking to get the proper behavior.
12040
12041 // This same functionality is important on PPC64 when dealing with
12042 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12043 // the return values of functions. Because it is so similar, it is handled
12044 // here as well.
12045
12046 if (N->getValueType(0) != MVT::i32 &&
12047 N->getValueType(0) != MVT::i64)
12048 return SDValue();
12049
12050 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12051 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12052 return SDValue();
12053
12054 if (N->getOperand(0).getOpcode() != ISD::AND &&
12055 N->getOperand(0).getOpcode() != ISD::OR &&
12056 N->getOperand(0).getOpcode() != ISD::XOR &&
12057 N->getOperand(0).getOpcode() != ISD::SELECT &&
12058 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12059 return SDValue();
12060
12061 SmallVector<SDValue, 4> Inputs;
12062 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12063 SmallPtrSet<SDNode *, 16> Visited;
12064
12065 // Visit all inputs, collect all binary operations (and, or, xor and
12066 // select) that are all fed by truncations.
12067 while (!BinOps.empty()) {
12068 SDValue BinOp = BinOps.back();
12069 BinOps.pop_back();
12070
12071 if (!Visited.insert(BinOp.getNode()).second)
12072 continue;
12073
12074 PromOps.push_back(BinOp);
12075
12076 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12077 // The condition of the select is not promoted.
12078 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12079 continue;
12080 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12081 continue;
12082
12083 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12084 isa<ConstantSDNode>(BinOp.getOperand(i))) {
12085 Inputs.push_back(BinOp.getOperand(i));
12086 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12087 BinOp.getOperand(i).getOpcode() == ISD::OR ||
12088 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12089 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12090 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12091 BinOps.push_back(BinOp.getOperand(i));
12092 } else {
12093 // We have an input that is not a truncation or another binary
12094 // operation; we'll abort this transformation.
12095 return SDValue();
12096 }
12097 }
12098 }
12099
12100 // The operands of a select that must be truncated when the select is
12101 // promoted because the operand is actually part of the to-be-promoted set.
12102 DenseMap<SDNode *, EVT> SelectTruncOp[2];
12103
12104 // Make sure that this is a self-contained cluster of operations (which
12105 // is not quite the same thing as saying that everything has only one
12106 // use).
12107 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12108 if (isa<ConstantSDNode>(Inputs[i]))
12109 continue;
12110
12111 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12112 UE = Inputs[i].getNode()->use_end();
12113 UI != UE; ++UI) {
12114 SDNode *User = *UI;
12115 if (User != N && !Visited.count(User))
12116 return SDValue();
12117
12118 // If we're going to promote the non-output-value operand(s) or SELECT or
12119 // SELECT_CC, record them for truncation.
12120 if (User->getOpcode() == ISD::SELECT) {
12121 if (User->getOperand(0) == Inputs[i])
12122 SelectTruncOp[0].insert(std::make_pair(User,
12123 User->getOperand(0).getValueType()));
12124 } else if (User->getOpcode() == ISD::SELECT_CC) {
12125 if (User->getOperand(0) == Inputs[i])
12126 SelectTruncOp[0].insert(std::make_pair(User,
12127 User->getOperand(0).getValueType()));
12128 if (User->getOperand(1) == Inputs[i])
12129 SelectTruncOp[1].insert(std::make_pair(User,
12130 User->getOperand(1).getValueType()));
12131 }
12132 }
12133 }
12134
12135 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12136 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12137 UE = PromOps[i].getNode()->use_end();
12138 UI != UE; ++UI) {
12139 SDNode *User = *UI;
12140 if (User != N && !Visited.count(User))
12141 return SDValue();
12142
12143 // If we're going to promote the non-output-value operand(s) or SELECT or
12144 // SELECT_CC, record them for truncation.
12145 if (User->getOpcode() == ISD::SELECT) {
12146 if (User->getOperand(0) == PromOps[i])
12147 SelectTruncOp[0].insert(std::make_pair(User,
12148 User->getOperand(0).getValueType()));
12149 } else if (User->getOpcode() == ISD::SELECT_CC) {
12150 if (User->getOperand(0) == PromOps[i])
12151 SelectTruncOp[0].insert(std::make_pair(User,
12152 User->getOperand(0).getValueType()));
12153 if (User->getOperand(1) == PromOps[i])
12154 SelectTruncOp[1].insert(std::make_pair(User,
12155 User->getOperand(1).getValueType()));
12156 }
12157 }
12158 }
12159
12160 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12161 bool ReallyNeedsExt = false;
12162 if (N->getOpcode() != ISD::ANY_EXTEND) {
12163 // If all of the inputs are not already sign/zero extended, then
12164 // we'll still need to do that at the end.
12165 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12166 if (isa<ConstantSDNode>(Inputs[i]))
12167 continue;
12168
12169 unsigned OpBits =
12170 Inputs[i].getOperand(0).getValueSizeInBits();
12171 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12172
12173 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12174 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12175 APInt::getHighBitsSet(OpBits,
12176 OpBits-PromBits))) ||
12177 (N->getOpcode() == ISD::SIGN_EXTEND &&
12178 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12179 (OpBits-(PromBits-1)))) {
12180 ReallyNeedsExt = true;
12181 break;
12182 }
12183 }
12184 }
12185
12186 // Replace all inputs, either with the truncation operand, or a
12187 // truncation or extension to the final output type.
12188 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12189 // Constant inputs need to be replaced with the to-be-promoted nodes that
12190 // use them because they might have users outside of the cluster of
12191 // promoted nodes.
12192 if (isa<ConstantSDNode>(Inputs[i]))
12193 continue;
12194
12195 SDValue InSrc = Inputs[i].getOperand(0);
12196 if (Inputs[i].getValueType() == N->getValueType(0))
12197 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12198 else if (N->getOpcode() == ISD::SIGN_EXTEND)
12199 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12200 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12201 else if (N->getOpcode() == ISD::ZERO_EXTEND)
12202 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12203 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12204 else
12205 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12206 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12207 }
12208
12209 std::list<HandleSDNode> PromOpHandles;
12210 for (auto &PromOp : PromOps)
12211 PromOpHandles.emplace_back(PromOp);
12212
12213 // Replace all operations (these are all the same, but have a different
12214 // (promoted) return type). DAG.getNode will validate that the types of
12215 // a binary operator match, so go through the list in reverse so that
12216 // we've likely promoted both operands first.
12217 while (!PromOpHandles.empty()) {
12218 SDValue PromOp = PromOpHandles.back().getValue();
12219 PromOpHandles.pop_back();
12220
12221 unsigned C;
12222 switch (PromOp.getOpcode()) {
12223 default: C = 0; break;
12224 case ISD::SELECT: C = 1; break;
12225 case ISD::SELECT_CC: C = 2; break;
12226 }
12227
12228 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12229 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12230 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12231 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12232 // The to-be-promoted operands of this node have not yet been
12233 // promoted (this should be rare because we're going through the
12234 // list backward, but if one of the operands has several users in
12235 // this cluster of to-be-promoted nodes, it is possible).
12236 PromOpHandles.emplace_front(PromOp);
12237 continue;
12238 }
12239
12240 // For SELECT and SELECT_CC nodes, we do a similar check for any
12241 // to-be-promoted comparison inputs.
12242 if (PromOp.getOpcode() == ISD::SELECT ||
12243 PromOp.getOpcode() == ISD::SELECT_CC) {
12244 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12245 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12246 (SelectTruncOp[1].count(PromOp.getNode()) &&
12247 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12248 PromOpHandles.emplace_front(PromOp);
12249 continue;
12250 }
12251 }
12252
12253 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12254 PromOp.getNode()->op_end());
12255
12256 // If this node has constant inputs, then they'll need to be promoted here.
12257 for (unsigned i = 0; i < 2; ++i) {
12258 if (!isa<ConstantSDNode>(Ops[C+i]))
12259 continue;
12260 if (Ops[C+i].getValueType() == N->getValueType(0))
12261 continue;
12262
12263 if (N->getOpcode() == ISD::SIGN_EXTEND)
12264 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12265 else if (N->getOpcode() == ISD::ZERO_EXTEND)
12266 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12267 else
12268 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12269 }
12270
12271 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12272 // truncate them again to the original value type.
12273 if (PromOp.getOpcode() == ISD::SELECT ||
12274 PromOp.getOpcode() == ISD::SELECT_CC) {
12275 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12276 if (SI0 != SelectTruncOp[0].end())
12277 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12278 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12279 if (SI1 != SelectTruncOp[1].end())
12280 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12281 }
12282
12283 DAG.ReplaceAllUsesOfValueWith(PromOp,
12284 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12285 }
12286
12287 // Now we're left with the initial extension itself.
12288 if (!ReallyNeedsExt)
12289 return N->getOperand(0);
12290
12291 // To zero extend, just mask off everything except for the first bit (in the
12292 // i1 case).
12293 if (N->getOpcode() == ISD::ZERO_EXTEND)
12294 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12295 DAG.getConstant(APInt::getLowBitsSet(
12296 N->getValueSizeInBits(0), PromBits),
12297 dl, N->getValueType(0)));
12298
12299 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12300 "Invalid extension type");
12301 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12302 SDValue ShiftCst =
12303 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12304 return DAG.getNode(
12305 ISD::SRA, dl, N->getValueType(0),
12306 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12307 ShiftCst);
12308}
12309
12310SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12311 DAGCombinerInfo &DCI) const {
12312 assert(N->getOpcode() == ISD::SETCC &&
12313 "Should be called with a SETCC node");
12314
12315 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12316 if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12317 SDValue LHS = N->getOperand(0);
12318 SDValue RHS = N->getOperand(1);
12319
12320 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12321 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12322 LHS.hasOneUse())
12323 std::swap(LHS, RHS);
12324
12325 // x == 0-y --> x+y == 0
12326 // x != 0-y --> x+y != 0
12327 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12328 RHS.hasOneUse()) {
12329 SDLoc DL(N);
12330 SelectionDAG &DAG = DCI.DAG;
12331 EVT VT = N->getValueType(0);
12332 EVT OpVT = LHS.getValueType();
12333 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12334 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12335 }
12336 }
12337
12338 return DAGCombineTruncBoolExt(N, DCI);
12339}
12340
12341// Is this an extending load from an f32 to an f64?
12342static bool isFPExtLoad(SDValue Op) {
12343 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12344 return LD->getExtensionType() == ISD::EXTLOAD &&
12345 Op.getValueType() == MVT::f64;
12346 return false;
12347}
12348
12349/// Reduces the number of fp-to-int conversion when building a vector.
12350///
12351/// If this vector is built out of floating to integer conversions,
12352/// transform it to a vector built out of floating point values followed by a
12353/// single floating to integer conversion of the vector.
12354/// Namely (build_vector (fptosi $A), (fptosi $B), ...)
12355/// becomes (fptosi (build_vector ($A, $B, ...)))
12356SDValue PPCTargetLowering::
12357combineElementTruncationToVectorTruncation(SDNode *N,
12358 DAGCombinerInfo &DCI) const {
12359 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12360 "Should be called with a BUILD_VECTOR node");
12361
12362 SelectionDAG &DAG = DCI.DAG;
12363 SDLoc dl(N);
12364
12365 SDValue FirstInput = N->getOperand(0);
12366 assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12367 "The input operand must be an fp-to-int conversion.");
12368
12369 // This combine happens after legalization so the fp_to_[su]i nodes are
12370 // already converted to PPCSISD nodes.
12371 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12372 if (FirstConversion == PPCISD::FCTIDZ ||
12373 FirstConversion == PPCISD::FCTIDUZ ||
12374 FirstConversion == PPCISD::FCTIWZ ||
12375 FirstConversion == PPCISD::FCTIWUZ) {
12376 bool IsSplat = true;
12377 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12378 FirstConversion == PPCISD::FCTIWUZ;
12379 EVT SrcVT = FirstInput.getOperand(0).getValueType();
12380 SmallVector<SDValue, 4> Ops;
12381 EVT TargetVT = N->getValueType(0);
12382 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12383 SDValue NextOp = N->getOperand(i);
12384 if (NextOp.getOpcode() != PPCISD::MFVSR)
12385 return SDValue();
12386 unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12387 if (NextConversion != FirstConversion)
12388 return SDValue();
12389 // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12390 // This is not valid if the input was originally double precision. It is
12391 // also not profitable to do unless this is an extending load in which
12392 // case doing this combine will allow us to combine consecutive loads.
12393 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12394 return SDValue();
12395 if (N->getOperand(i) != FirstInput)
12396 IsSplat = false;
12397 }
12398
12399 // If this is a splat, we leave it as-is since there will be only a single
12400 // fp-to-int conversion followed by a splat of the integer. This is better
12401 // for 32-bit and smaller ints and neutral for 64-bit ints.
12402 if (IsSplat)
12403 return SDValue();
12404
12405 // Now that we know we have the right type of node, get its operands
12406 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12407 SDValue In = N->getOperand(i).getOperand(0);
12408 if (Is32Bit) {
12409 // For 32-bit values, we need to add an FP_ROUND node (if we made it
12410 // here, we know that all inputs are extending loads so this is safe).
12411 if (In.isUndef())
12412 Ops.push_back(DAG.getUNDEF(SrcVT));
12413 else {
12414 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12415 MVT::f32, In.getOperand(0),
12416 DAG.getIntPtrConstant(1, dl));
12417 Ops.push_back(Trunc);
12418 }
12419 } else
12420 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12421 }
12422
12423 unsigned Opcode;
12424 if (FirstConversion == PPCISD::FCTIDZ ||
12425 FirstConversion == PPCISD::FCTIWZ)
12426 Opcode = ISD::FP_TO_SINT;
12427 else
12428 Opcode = ISD::FP_TO_UINT;
12429
12430 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12431 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12432 return DAG.getNode(Opcode, dl, TargetVT, BV);
12433 }
12434 return SDValue();
12435}
12436
12437/// Reduce the number of loads when building a vector.
12438///
12439/// Building a vector out of multiple loads can be converted to a load
12440/// of the vector type if the loads are consecutive. If the loads are
12441/// consecutive but in descending order, a shuffle is added at the end
12442/// to reorder the vector.
12443static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12444 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12445 "Should be called with a BUILD_VECTOR node");
12446
12447 SDLoc dl(N);
12448
12449 // Return early for non byte-sized type, as they can't be consecutive.
12450 if (!N->getValueType(0).getVectorElementType().isByteSized())
12451 return SDValue();
12452
12453 bool InputsAreConsecutiveLoads = true;
12454 bool InputsAreReverseConsecutive = true;
12455 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12456 SDValue FirstInput = N->getOperand(0);
12457 bool IsRoundOfExtLoad = false;
12458
12459 if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12460 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12461 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12462 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12463 }
12464 // Not a build vector of (possibly fp_rounded) loads.
12465 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12466 N->getNumOperands() == 1)
12467 return SDValue();
12468
12469 for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12470 // If any inputs are fp_round(extload), they all must be.
12471 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12472 return SDValue();
12473
12474 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
12475 N->getOperand(i);
12476 if (NextInput.getOpcode() != ISD::LOAD)
12477 return SDValue();
12478
12479 SDValue PreviousInput =
12480 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
12481 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
12482 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
12483
12484 // If any inputs are fp_round(extload), they all must be.
12485 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
12486 return SDValue();
12487
12488 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
12489 InputsAreConsecutiveLoads = false;
12490 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
12491 InputsAreReverseConsecutive = false;
12492
12493 // Exit early if the loads are neither consecutive nor reverse consecutive.
12494 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
12495 return SDValue();
12496 }
12497
12498 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
12499 "The loads cannot be both consecutive and reverse consecutive.");
12500
12501 SDValue FirstLoadOp =
12502 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
12503 SDValue LastLoadOp =
12504 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
12505 N->getOperand(N->getNumOperands()-1);
12506
12507 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
12508 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
12509 if (InputsAreConsecutiveLoads) {
12510 assert(LD1 && "Input needs to be a LoadSDNode.");
12511 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
12512 LD1->getBasePtr(), LD1->getPointerInfo(),
12513 LD1->getAlignment());
12514 }
12515 if (InputsAreReverseConsecutive) {
12516 assert(LDL && "Input needs to be a LoadSDNode.");
12517 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
12518 LDL->getBasePtr(), LDL->getPointerInfo(),
12519 LDL->getAlignment());
12520 SmallVector<int, 16> Ops;
12521 for (int i = N->getNumOperands() - 1; i >= 0; i--)
12522 Ops.push_back(i);
12523
12524 return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
12525 DAG.getUNDEF(N->getValueType(0)), Ops);
12526 }
12527 return SDValue();
12528}
12529
12530// This function adds the required vector_shuffle needed to get
12531// the elements of the vector extract in the correct position
12532// as specified by the CorrectElems encoding.
12533static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
12534 SDValue Input, uint64_t Elems,
12535 uint64_t CorrectElems) {
12536 SDLoc dl(N);
12537
12538 unsigned NumElems = Input.getValueType().getVectorNumElements();
12539 SmallVector<int, 16> ShuffleMask(NumElems, -1);
12540
12541 // Knowing the element indices being extracted from the original
12542 // vector and the order in which they're being inserted, just put
12543 // them at element indices required for the instruction.
12544 for (unsigned i = 0; i < N->getNumOperands(); i++) {
12545 if (DAG.getDataLayout().isLittleEndian())
12546 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
12547 else
12548 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
12549 CorrectElems = CorrectElems >> 8;
12550 Elems = Elems >> 8;
12551 }
12552
12553 SDValue Shuffle =
12554 DAG.getVectorShuffle(Input.getValueType(), dl, Input,
12555 DAG.getUNDEF(Input.getValueType()), ShuffleMask);
12556
12557 EVT Ty = N->getValueType(0);
12558 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
12559 return BV;
12560}
12561
12562// Look for build vector patterns where input operands come from sign
12563// extended vector_extract elements of specific indices. If the correct indices
12564// aren't used, add a vector shuffle to fix up the indices and create a new
12565// PPCISD:SExtVElems node which selects the vector sign extend instructions
12566// during instruction selection.
12567static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
12568 // This array encodes the indices that the vector sign extend instructions
12569 // extract from when extending from one type to another for both BE and LE.
12570 // The right nibble of each byte corresponds to the LE incides.
12571 // and the left nibble of each byte corresponds to the BE incides.
12572 // For example: 0x3074B8FC byte->word
12573 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
12574 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
12575 // For example: 0x000070F8 byte->double word
12576 // For LE: the allowed indices are: 0x0,0x8
12577 // For BE: the allowed indices are: 0x7,0xF
12578 uint64_t TargetElems[] = {
12579 0x3074B8FC, // b->w
12580 0x000070F8, // b->d
12581 0x10325476, // h->w
12582 0x00003074, // h->d
12583 0x00001032, // w->d
12584 };
12585
12586 uint64_t Elems = 0;
12587 int Index;
12588 SDValue Input;
12589
12590 auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
12591 if (!Op)
12592 return false;
12593 if (Op.getOpcode() != ISD::SIGN_EXTEND &&
12594 Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
12595 return false;
12596
12597 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
12598 // of the right width.
12599 SDValue Extract = Op.getOperand(0);
12600 if (Extract.getOpcode() == ISD::ANY_EXTEND)
12601 Extract = Extract.getOperand(0);
12602 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12603 return false;
12604
12605 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
12606 if (!ExtOp)
12607 return false;
12608
12609 Index = ExtOp->getZExtValue();
12610 if (Input && Input != Extract.getOperand(0))
12611 return false;
12612
12613 if (!Input)
12614 Input = Extract.getOperand(0);
12615
12616 Elems = Elems << 8;
12617 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
12618 Elems |= Index;
12619
12620 return true;
12621 };
12622
12623 // If the build vector operands aren't sign extended vector extracts,
12624 // of the same input vector, then return.
12625 for (unsigned i = 0; i < N->getNumOperands(); i++) {
12626 if (!isSExtOfVecExtract(N->getOperand(i))) {
12627 return SDValue();
12628 }
12629 }
12630
12631 // If the vector extract indicies are not correct, add the appropriate
12632 // vector_shuffle.
12633 int TgtElemArrayIdx;
12634 int InputSize = Input.getValueType().getScalarSizeInBits();
12635 int OutputSize = N->getValueType(0).getScalarSizeInBits();
12636 if (InputSize + OutputSize == 40)
12637 TgtElemArrayIdx = 0;
12638 else if (InputSize + OutputSize == 72)
12639 TgtElemArrayIdx = 1;
12640 else if (InputSize + OutputSize == 48)
12641 TgtElemArrayIdx = 2;
12642 else if (InputSize + OutputSize == 80)
12643 TgtElemArrayIdx = 3;
12644 else if (InputSize + OutputSize == 96)
12645 TgtElemArrayIdx = 4;
12646 else
12647 return SDValue();
12648
12649 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
12650 CorrectElems = DAG.getDataLayout().isLittleEndian()
12651 ? CorrectElems & 0x0F0F0F0F0F0F0F0F
12652 : CorrectElems & 0xF0F0F0F0F0F0F0F0;
12653 if (Elems != CorrectElems) {
12654 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
12655 }
12656
12657 // Regular lowering will catch cases where a shuffle is not needed.
12658 return SDValue();
12659}
12660
12661SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
12662 DAGCombinerInfo &DCI) const {
12663 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12664 "Should be called with a BUILD_VECTOR node");
12665
12666 SelectionDAG &DAG = DCI.DAG;
12667 SDLoc dl(N);
12668
12669 if (!Subtarget.hasVSX())
12670 return SDValue();
12671
12672 // The target independent DAG combiner will leave a build_vector of
12673 // float-to-int conversions intact. We can generate MUCH better code for
12674 // a float-to-int conversion of a vector of floats.
12675 SDValue FirstInput = N->getOperand(0);
12676 if (FirstInput.getOpcode() == PPCISD::MFVSR) {
12677 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
12678 if (Reduced)
12679 return Reduced;
12680 }
12681
12682 // If we're building a vector out of consecutive loads, just load that
12683 // vector type.
12684 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
12685 if (Reduced)
12686 return Reduced;
12687
12688 // If we're building a vector out of extended elements from another vector
12689 // we have P9 vector integer extend instructions. The code assumes legal
12690 // input types (i.e. it can't handle things like v4i16) so do not run before
12691 // legalization.
12692 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
12693 Reduced = combineBVOfVecSExt(N, DAG);
12694 if (Reduced)
12695 return Reduced;
12696 }
12697
12698
12699 if (N->getValueType(0) != MVT::v2f64)
12700 return SDValue();
12701
12702 // Looking for:
12703 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
12704 if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
12705 FirstInput.getOpcode() != ISD::UINT_TO_FP)
12706 return SDValue();
12707 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
12708 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
12709 return SDValue();
12710 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
12711 return SDValue();
12712
12713 SDValue Ext1 = FirstInput.getOperand(0);
12714 SDValue Ext2 = N->getOperand(1).getOperand(0);
12715 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12716 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12717 return SDValue();
12718
12719 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
12720 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
12721 if (!Ext1Op || !Ext2Op)
12722 return SDValue();
12723 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
12724 Ext1.getOperand(0) != Ext2.getOperand(0))
12725 return SDValue();
12726
12727 int FirstElem = Ext1Op->getZExtValue();
12728 int SecondElem = Ext2Op->getZExtValue();
12729 int SubvecIdx;
12730 if (FirstElem == 0 && SecondElem == 1)
12731 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
12732 else if (FirstElem == 2 && SecondElem == 3)
12733 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
12734 else
12735 return SDValue();
12736
12737 SDValue SrcVec = Ext1.getOperand(0);
12738 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
12739 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
12740 return DAG.getNode(NodeType, dl, MVT::v2f64,
12741 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
12742}
12743
12744SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
12745 DAGCombinerInfo &DCI) const {
12746 assert((N->getOpcode() == ISD::SINT_TO_FP ||
12747 N->getOpcode() == ISD::UINT_TO_FP) &&
12748 "Need an int -> FP conversion node here");
12749
12750 if (useSoftFloat() || !Subtarget.has64BitSupport())
12751 return SDValue();
12752
12753 SelectionDAG &DAG = DCI.DAG;
12754 SDLoc dl(N);
12755 SDValue Op(N, 0);
12756
12757 // Don't handle ppc_fp128 here or conversions that are out-of-range capable
12758 // from the hardware.
12759 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
12760 return SDValue();
12761 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
12762 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
12763 return SDValue();
12764
12765 SDValue FirstOperand(Op.getOperand(0));
12766 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
12767 (FirstOperand.getValueType() == MVT::i8 ||
12768 FirstOperand.getValueType() == MVT::i16);
12769 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
12770 bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
12771 bool DstDouble = Op.getValueType() == MVT::f64;
12772 unsigned ConvOp = Signed ?
12773 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
12774 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
12775 SDValue WidthConst =
12776 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
12777 dl, false);
12778 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
12779 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
12780 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
12781 DAG.getVTList(MVT::f64, MVT::Other),
12782 Ops, MVT::i8, LDN->getMemOperand());
12783
12784 // For signed conversion, we need to sign-extend the value in the VSR
12785 if (Signed) {
12786 SDValue ExtOps[] = { Ld, WidthConst };
12787 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
12788 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
12789 } else
12790 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
12791 }
12792
12793
12794 // For i32 intermediate values, unfortunately, the conversion functions
12795 // leave the upper 32 bits of the value are undefined. Within the set of
12796 // scalar instructions, we have no method for zero- or sign-extending the
12797 // value. Thus, we cannot handle i32 intermediate values here.
12798 if (Op.getOperand(0).getValueType() == MVT::i32)
12799 return SDValue();
12800
12801 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
12802 "UINT_TO_FP is supported only with FPCVT");
12803
12804 // If we have FCFIDS, then use it when converting to single-precision.
12805 // Otherwise, convert to double-precision and then round.
12806 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12807 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
12808 : PPCISD::FCFIDS)
12809 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
12810 : PPCISD::FCFID);
12811 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12812 ? MVT::f32
12813 : MVT::f64;
12814
12815 // If we're converting from a float, to an int, and back to a float again,
12816 // then we don't need the store/load pair at all.
12817 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
12818 Subtarget.hasFPCVT()) ||
12819 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
12820 SDValue Src = Op.getOperand(0).getOperand(0);
12821 if (Src.getValueType() == MVT::f32) {
12822 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
12823 DCI.AddToWorklist(Src.getNode());
12824 } else if (Src.getValueType() != MVT::f64) {
12825 // Make sure that we don't pick up a ppc_fp128 source value.
12826 return SDValue();
12827 }
12828
12829 unsigned FCTOp =
12830 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
12831 PPCISD::FCTIDUZ;
12832
12833 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
12834 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
12835
12836 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
12837 FP = DAG.getNode(ISD::FP_ROUND, dl,
12838 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
12839 DCI.AddToWorklist(FP.getNode());
12840 }
12841
12842 return FP;
12843 }
12844
12845 return SDValue();
12846}
12847
12848// expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
12849// builtins) into loads with swaps.
12850SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
12851 DAGCombinerInfo &DCI) const {
12852 SelectionDAG &DAG = DCI.DAG;
12853 SDLoc dl(N);
12854 SDValue Chain;
12855 SDValue Base;
12856 MachineMemOperand *MMO;
12857
12858 switch (N->getOpcode()) {
12859 default:
12860 llvm_unreachable("Unexpected opcode for little endian VSX load");
12861 case ISD::LOAD: {
12862 LoadSDNode *LD = cast<LoadSDNode>(N);
12863 Chain = LD->getChain();
12864 Base = LD->getBasePtr();
12865 MMO = LD->getMemOperand();
12866 // If the MMO suggests this isn't a load of a full vector, leave
12867 // things alone. For a built-in, we have to make the change for
12868 // correctness, so if there is a size problem that will be a bug.
12869 if (MMO->getSize() < 16)
12870 return SDValue();
12871 break;
12872 }
12873 case ISD::INTRINSIC_W_CHAIN: {
12874 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12875 Chain = Intrin->getChain();
12876 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
12877 // us what we want. Get operand 2 instead.
12878 Base = Intrin->getOperand(2);
12879 MMO = Intrin->getMemOperand();
12880 break;
12881 }
12882 }
12883
12884 MVT VecTy = N->getValueType(0).getSimpleVT();
12885
12886 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
12887 // aligned and the type is a vector with elements up to 4 bytes
12888 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12889 && VecTy.getScalarSizeInBits() <= 32 ) {
12890 return SDValue();
12891 }
12892
12893 SDValue LoadOps[] = { Chain, Base };
12894 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
12895 DAG.getVTList(MVT::v2f64, MVT::Other),
12896 LoadOps, MVT::v2f64, MMO);
12897
12898 DCI.AddToWorklist(Load.getNode());
12899 Chain = Load.getValue(1);
12900 SDValue Swap = DAG.getNode(
12901 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
12902 DCI.AddToWorklist(Swap.getNode());
12903
12904 // Add a bitcast if the resulting load type doesn't match v2f64.
12905 if (VecTy != MVT::v2f64) {
12906 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12907 DCI.AddToWorklist(N.getNode());
12908 // Package {bitcast value, swap's chain} to match Load's shape.
12909 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12910 N, Swap.getValue(1));
12911 }
12912
12913 return Swap;
12914}
12915
12916// expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12917// builtins) into stores with swaps.
12918SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
12919 DAGCombinerInfo &DCI) const {
12920 SelectionDAG &DAG = DCI.DAG;
12921 SDLoc dl(N);
12922 SDValue Chain;
12923 SDValue Base;
12924 unsigned SrcOpnd;
12925 MachineMemOperand *MMO;
12926
12927 switch (N->getOpcode()) {
12928 default:
12929 llvm_unreachable("Unexpected opcode for little endian VSX store");
12930 case ISD::STORE: {
12931 StoreSDNode *ST = cast<StoreSDNode>(N);
12932 Chain = ST->getChain();
12933 Base = ST->getBasePtr();
12934 MMO = ST->getMemOperand();
12935 SrcOpnd = 1;
12936 // If the MMO suggests this isn't a store of a full vector, leave
12937 // things alone. For a built-in, we have to make the change for
12938 // correctness, so if there is a size problem that will be a bug.
12939 if (MMO->getSize() < 16)
12940 return SDValue();
12941 break;
12942 }
12943 case ISD::INTRINSIC_VOID: {
12944 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12945 Chain = Intrin->getChain();
12946 // Intrin->getBasePtr() oddly does not get what we want.
12947 Base = Intrin->getOperand(3);
12948 MMO = Intrin->getMemOperand();
12949 SrcOpnd = 2;
12950 break;
12951 }
12952 }
12953
12954 SDValue Src = N->getOperand(SrcOpnd);
12955 MVT VecTy = Src.getValueType().getSimpleVT();
12956
12957 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
12958 // aligned and the type is a vector with elements up to 4 bytes
12959 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12960 && VecTy.getScalarSizeInBits() <= 32 ) {
12961 return SDValue();
12962 }
12963
12964 // All stores are done as v2f64 and possible bit cast.
12965 if (VecTy != MVT::v2f64) {
12966 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
12967 DCI.AddToWorklist(Src.getNode());
12968 }
12969
12970 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
12971 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
12972 DCI.AddToWorklist(Swap.getNode());
12973 Chain = Swap.getValue(1);
12974 SDValue StoreOps[] = { Chain, Swap, Base };
12975 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
12976 DAG.getVTList(MVT::Other),
12977 StoreOps, VecTy, MMO);
12978 DCI.AddToWorklist(Store.getNode());
12979 return Store;
12980}
12981
12982// Handle DAG combine for STORE (FP_TO_INT F).
12983SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
12984 DAGCombinerInfo &DCI) const {
12985
12986 SelectionDAG &DAG = DCI.DAG;
12987 SDLoc dl(N);
12988 unsigned Opcode = N->getOperand(1).getOpcode();
12989
12990 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
12991 && "Not a FP_TO_INT Instruction!");
12992
12993 SDValue Val = N->getOperand(1).getOperand(0);
12994 EVT Op1VT = N->getOperand(1).getValueType();
12995 EVT ResVT = Val.getValueType();
12996
12997 // Floating point types smaller than 32 bits are not legal on Power.
12998 if (ResVT.getScalarSizeInBits() < 32)
12999 return SDValue();
13000
13001 // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13002 bool ValidTypeForStoreFltAsInt =
13003 (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13004 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13005
13006 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13007 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13008 return SDValue();
13009
13010 // Extend f32 values to f64
13011 if (ResVT.getScalarSizeInBits() == 32) {
13012 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13013 DCI.AddToWorklist(Val.getNode());
13014 }
13015
13016 // Set signed or unsigned conversion opcode.
13017 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13018 PPCISD::FP_TO_SINT_IN_VSR :
13019 PPCISD::FP_TO_UINT_IN_VSR;
13020
13021 Val = DAG.getNode(ConvOpcode,
13022 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13023 DCI.AddToWorklist(Val.getNode());
13024
13025 // Set number of bytes being converted.
13026 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13027 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13028 DAG.getIntPtrConstant(ByteSize, dl, false),
13029 DAG.getValueType(Op1VT) };
13030
13031 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13032 DAG.getVTList(MVT::Other), Ops,
13033 cast<StoreSDNode>(N)->getMemoryVT(),
13034 cast<StoreSDNode>(N)->getMemOperand());
13035
13036 DCI.AddToWorklist(Val.getNode());
13037 return Val;
13038}
13039
13040SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13041 DAGCombinerInfo &DCI) const {
13042 SelectionDAG &DAG = DCI.DAG;
13043 SDLoc dl(N);
13044 switch (N->getOpcode()) {
13045 default: break;
13046 case ISD::ADD:
13047 return combineADD(N, DCI);
13048 case ISD::SHL:
13049 return combineSHL(N, DCI);
13050 case ISD::SRA:
13051 return combineSRA(N, DCI);
13052 case ISD::SRL:
13053 return combineSRL(N, DCI);
13054 case ISD::MUL:
13055 return combineMUL(N, DCI);
13056 case PPCISD::SHL:
13057 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13058 return N->getOperand(0);
13059 break;
13060 case PPCISD::SRL:
13061 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13062 return N->getOperand(0);
13063 break;
13064 case PPCISD::SRA:
13065 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13066 if (C->isNullValue() || // 0 >>s V -> 0.
13067 C->isAllOnesValue()) // -1 >>s V -> -1.
13068 return N->getOperand(0);
13069 }
13070 break;
13071 case ISD::SIGN_EXTEND:
13072 case ISD::ZERO_EXTEND:
13073 case ISD::ANY_EXTEND:
13074 return DAGCombineExtBoolTrunc(N, DCI);
13075 case ISD::TRUNCATE:
13076 return combineTRUNCATE(N, DCI);
13077 case ISD::SETCC:
13078 if (SDValue CSCC = combineSetCC(N, DCI))
13079 return CSCC;
13080 LLVM_FALLTHROUGH;
13081 case ISD::SELECT_CC:
13082 return DAGCombineTruncBoolExt(N, DCI);
13083 case ISD::SINT_TO_FP:
13084 case ISD::UINT_TO_FP:
13085 return combineFPToIntToFP(N, DCI);
13086 case ISD::STORE: {
13087
13088 EVT Op1VT = N->getOperand(1).getValueType();
13089 unsigned Opcode = N->getOperand(1).getOpcode();
13090
13091 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13092 SDValue Val= combineStoreFPToInt(N, DCI);
13093 if (Val)
13094 return Val;
13095 }
13096
13097 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13098 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13099 N->getOperand(1).getNode()->hasOneUse() &&
13100 (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13101 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13102
13103 // STBRX can only handle simple types and it makes no sense to store less
13104 // two bytes in byte-reversed order.
13105 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13106 if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13107 break;
13108
13109 SDValue BSwapOp = N->getOperand(1).getOperand(0);
13110 // Do an any-extend to 32-bits if this is a half-word input.
13111 if (BSwapOp.getValueType() == MVT::i16)
13112 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13113
13114 // If the type of BSWAP operand is wider than stored memory width
13115 // it need to be shifted to the right side before STBRX.
13116 if (Op1VT.bitsGT(mVT)) {
13117 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13118 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13119 DAG.getConstant(Shift, dl, MVT::i32));
13120 // Need to truncate if this is a bswap of i64 stored as i32/i16.
13121 if (Op1VT == MVT::i64)
13122 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13123 }
13124
13125 SDValue Ops[] = {
13126 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13127 };
13128 return
13129 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13130 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13131 cast<StoreSDNode>(N)->getMemOperand());
13132 }
13133
13134 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0>
13135 // So it can increase the chance of CSE constant construction.
13136 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13137 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13138 // Need to sign-extended to 64-bits to handle negative values.
13139 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13140 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13141 MemVT.getSizeInBits());
13142 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13143
13144 // DAG.getTruncStore() can't be used here because it doesn't accept
13145 // the general (base + offset) addressing mode.
13146 // So we use UpdateNodeOperands and setTruncatingStore instead.
13147 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13148 N->getOperand(3));
13149 cast<StoreSDNode>(N)->setTruncatingStore(true);
13150 return SDValue(N, 0);
13151 }
13152
13153 // For little endian, VSX stores require generating xxswapd/lxvd2x.
13154 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13155 if (Op1VT.isSimple()) {
13156 MVT StoreVT = Op1VT.getSimpleVT();
13157 if (Subtarget.needsSwapsForVSXMemOps() &&
13158 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13159 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13160 return expandVSXStoreForLE(N, DCI);
13161 }
13162 break;
13163 }
13164 case ISD::LOAD: {
13165 LoadSDNode *LD = cast<LoadSDNode>(N);
13166 EVT VT = LD->getValueType(0);
13167
13168 // For little endian, VSX loads require generating lxvd2x/xxswapd.
13169 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13170 if (VT.isSimple()) {
13171 MVT LoadVT = VT.getSimpleVT();
13172 if (Subtarget.needsSwapsForVSXMemOps() &&
13173 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13174 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13175 return expandVSXLoadForLE(N, DCI);
13176 }
13177
13178 // We sometimes end up with a 64-bit integer load, from which we extract
13179 // two single-precision floating-point numbers. This happens with
13180 // std::complex<float>, and other similar structures, because of the way we
13181 // canonicalize structure copies. However, if we lack direct moves,
13182 // then the final bitcasts from the extracted integer values to the
13183 // floating-point numbers turn into store/load pairs. Even with direct moves,
13184 // just loading the two floating-point numbers is likely better.
13185 auto ReplaceTwoFloatLoad = [&]() {
13186 if (VT != MVT::i64)
13187 return false;
13188
13189 if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13190 LD->isVolatile())
13191 return false;
13192
13193 // We're looking for a sequence like this:
13194 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13195 // t16: i64 = srl t13, Constant:i32<32>
13196 // t17: i32 = truncate t16
13197 // t18: f32 = bitcast t17
13198 // t19: i32 = truncate t13
13199 // t20: f32 = bitcast t19
13200
13201 if (!LD->hasNUsesOfValue(2, 0))
13202 return false;
13203
13204 auto UI = LD->use_begin();
13205 while (UI.getUse().getResNo() != 0) ++UI;
13206 SDNode *Trunc = *UI++;
13207 while (UI.getUse().getResNo() != 0) ++UI;
13208 SDNode *RightShift = *UI;
13209 if (Trunc->getOpcode() != ISD::TRUNCATE)
13210 std::swap(Trunc, RightShift);
13211
13212 if (Trunc->getOpcode() != ISD::TRUNCATE ||
13213 Trunc->getValueType(0) != MVT::i32 ||
13214 !Trunc->hasOneUse())
13215 return false;
13216 if (RightShift->getOpcode() != ISD::SRL ||
13217 !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13218 RightShift->getConstantOperandVal(1) != 32 ||
13219 !RightShift->hasOneUse())
13220 return false;
13221
13222 SDNode *Trunc2 = *RightShift->use_begin();
13223 if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13224 Trunc2->getValueType(0) != MVT::i32 ||
13225 !Trunc2->hasOneUse())
13226 return false;
13227
13228 SDNode *Bitcast = *Trunc->use_begin();
13229 SDNode *Bitcast2 = *Trunc2->use_begin();
13230
13231 if (Bitcast->getOpcode() != ISD::BITCAST ||
13232 Bitcast->getValueType(0) != MVT::f32)
13233 return false;
13234 if (Bitcast2->getOpcode() != ISD::BITCAST ||
13235 Bitcast2->getValueType(0) != MVT::f32)
13236 return false;
13237
13238 if (Subtarget.isLittleEndian())
13239 std::swap(Bitcast, Bitcast2);
13240
13241 // Bitcast has the second float (in memory-layout order) and Bitcast2
13242 // has the first one.
13243
13244 SDValue BasePtr = LD->getBasePtr();
13245 if (LD->isIndexed()) {
13246 assert(LD->getAddressingMode() == ISD::PRE_INC &&
13247 "Non-pre-inc AM on PPC?");
13248 BasePtr =
13249 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13250 LD->getOffset());
13251 }
13252
13253 auto MMOFlags =
13254 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13255 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13256 LD->getPointerInfo(), LD->getAlignment(),
13257 MMOFlags, LD->getAAInfo());
13258 SDValue AddPtr =
13259 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13260 BasePtr, DAG.getIntPtrConstant(4, dl));
13261 SDValue FloatLoad2 = DAG.getLoad(
13262 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13263 LD->getPointerInfo().getWithOffset(4),
13264 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13265
13266 if (LD->isIndexed()) {
13267 // Note that DAGCombine should re-form any pre-increment load(s) from
13268 // what is produced here if that makes sense.
13269 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13270 }
13271
13272 DCI.CombineTo(Bitcast2, FloatLoad);
13273 DCI.CombineTo(Bitcast, FloatLoad2);
13274
13275 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13276 SDValue(FloatLoad2.getNode(), 1));
13277 return true;
13278 };
13279
13280 if (ReplaceTwoFloatLoad())
13281 return SDValue(N, 0);
13282
13283 EVT MemVT = LD->getMemoryVT();
13284 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13285 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13286 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13287 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13288 if (LD->isUnindexed() && VT.isVector() &&
13289 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13290 // P8 and later hardware should just use LOAD.
13291 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13292 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13293 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13294 LD->getAlignment() >= ScalarABIAlignment)) &&
13295 LD->getAlignment() < ABIAlignment) {
13296 // This is a type-legal unaligned Altivec or QPX load.
13297 SDValue Chain = LD->getChain();
13298 SDValue Ptr = LD->getBasePtr();
13299 bool isLittleEndian = Subtarget.isLittleEndian();
13300
13301 // This implements the loading of unaligned vectors as described in
13302 // the venerable Apple Velocity Engine overview. Specifically:
13303 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13304 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13305 //
13306 // The general idea is to expand a sequence of one or more unaligned
13307 // loads into an alignment-based permutation-control instruction (lvsl
13308 // or lvsr), a series of regular vector loads (which always truncate
13309 // their input address to an aligned address), and a series of
13310 // permutations. The results of these permutations are the requested
13311 // loaded values. The trick is that the last "extra" load is not taken
13312 // from the address you might suspect (sizeof(vector) bytes after the
13313 // last requested load), but rather sizeof(vector) - 1 bytes after the
13314 // last requested vector. The point of this is to avoid a page fault if
13315 // the base address happened to be aligned. This works because if the
13316 // base address is aligned, then adding less than a full vector length
13317 // will cause the last vector in the sequence to be (re)loaded.
13318 // Otherwise, the next vector will be fetched as you might suspect was
13319 // necessary.
13320
13321 // We might be able to reuse the permutation generation from
13322 // a different base address offset from this one by an aligned amount.
13323 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13324 // optimization later.
13325 Intrinsic::ID Intr, IntrLD, IntrPerm;
13326 MVT PermCntlTy, PermTy, LDTy;
13327 if (Subtarget.hasAltivec()) {
13328 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
13329 Intrinsic::ppc_altivec_lvsl;
13330 IntrLD = Intrinsic::ppc_altivec_lvx;
13331 IntrPerm = Intrinsic::ppc_altivec_vperm;
13332 PermCntlTy = MVT::v16i8;
13333 PermTy = MVT::v4i32;
13334 LDTy = MVT::v4i32;
13335 } else {
13336 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13337 Intrinsic::ppc_qpx_qvlpcls;
13338 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13339 Intrinsic::ppc_qpx_qvlfs;
13340 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13341 PermCntlTy = MVT::v4f64;
13342 PermTy = MVT::v4f64;
13343 LDTy = MemVT.getSimpleVT();
13344 }
13345
13346 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13347
13348 // Create the new MMO for the new base load. It is like the original MMO,
13349 // but represents an area in memory almost twice the vector size centered
13350 // on the original address. If the address is unaligned, we might start
13351 // reading up to (sizeof(vector)-1) bytes below the address of the
13352 // original unaligned load.
13353 MachineFunction &MF = DAG.getMachineFunction();
13354 MachineMemOperand *BaseMMO =
13355 MF.getMachineMemOperand(LD->getMemOperand(),
13356 -(long)MemVT.getStoreSize()+1,
13357 2*MemVT.getStoreSize()-1);
13358
13359 // Create the new base load.
13360 SDValue LDXIntID =
13361 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13362 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13363 SDValue BaseLoad =
13364 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13365 DAG.getVTList(PermTy, MVT::Other),
13366 BaseLoadOps, LDTy, BaseMMO);
13367
13368 // Note that the value of IncOffset (which is provided to the next
13369 // load's pointer info offset value, and thus used to calculate the
13370 // alignment), and the value of IncValue (which is actually used to
13371 // increment the pointer value) are different! This is because we
13372 // require the next load to appear to be aligned, even though it
13373 // is actually offset from the base pointer by a lesser amount.
13374 int IncOffset = VT.getSizeInBits() / 8;
13375 int IncValue = IncOffset;
13376
13377 // Walk (both up and down) the chain looking for another load at the real
13378 // (aligned) offset (the alignment of the other load does not matter in
13379 // this case). If found, then do not use the offset reduction trick, as
13380 // that will prevent the loads from being later combined (as they would
13381 // otherwise be duplicates).
13382 if (!findConsecutiveLoad(LD, DAG))
13383 --IncValue;
13384
13385 SDValue Increment =
13386 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13387 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13388
13389 MachineMemOperand *ExtraMMO =
13390 MF.getMachineMemOperand(LD->getMemOperand(),
13391 1, 2*MemVT.getStoreSize()-1);
13392 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13393 SDValue ExtraLoad =
13394 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13395 DAG.getVTList(PermTy, MVT::Other),
13396 ExtraLoadOps, LDTy, ExtraMMO);
13397
13398 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13399 BaseLoad.getValue(1), ExtraLoad.getValue(1));
13400
13401 // Because vperm has a big-endian bias, we must reverse the order
13402 // of the input vectors and complement the permute control vector
13403 // when generating little endian code. We have already handled the
13404 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13405 // and ExtraLoad here.
13406 SDValue Perm;
13407 if (isLittleEndian)
13408 Perm = BuildIntrinsicOp(IntrPerm,
13409 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
13410 else
13411 Perm = BuildIntrinsicOp(IntrPerm,
13412 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
13413
13414 if (VT != PermTy)
13415 Perm = Subtarget.hasAltivec() ?
13416 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
13417 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
13418 DAG.getTargetConstant(1, dl, MVT::i64));
13419 // second argument is 1 because this rounding
13420 // is always exact.
13421
13422 // The output of the permutation is our loaded result, the TokenFactor is
13423 // our new chain.
13424 DCI.CombineTo(N, Perm, TF);
13425 return SDValue(N, 0);
13426 }
13427 }
13428 break;
13429 case ISD::INTRINSIC_WO_CHAIN: {
13430 bool isLittleEndian = Subtarget.isLittleEndian();
13431 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13432 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
13433 : Intrinsic::ppc_altivec_lvsl);
13434 if ((IID == Intr ||
13435 IID == Intrinsic::ppc_qpx_qvlpcld ||
13436 IID == Intrinsic::ppc_qpx_qvlpcls) &&
13437 N->getOperand(1)->getOpcode() == ISD::ADD) {
13438 SDValue Add = N->getOperand(1);
13439
13440 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
13441 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
13442
13443 if (DAG.MaskedValueIsZero(Add->getOperand(1),
13444 APInt::getAllOnesValue(Bits /* alignment */)
13445 .zext(Add.getScalarValueSizeInBits()))) {
13446 SDNode *BasePtr = Add->getOperand(0).getNode();
13447 for (SDNode::use_iterator UI = BasePtr->use_begin(),
13448 UE = BasePtr->use_end();
13449 UI != UE; ++UI) {
13450 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13451 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
13452 // We've found another LVSL/LVSR, and this address is an aligned
13453 // multiple of that one. The results will be the same, so use the
13454 // one we've just found instead.
13455
13456 return SDValue(*UI, 0);
13457 }
13458 }
13459 }
13460
13461 if (isa<ConstantSDNode>(Add->getOperand(1))) {
13462 SDNode *BasePtr = Add->getOperand(0).getNode();
13463 for (SDNode::use_iterator UI = BasePtr->use_begin(),
13464 UE = BasePtr->use_end(); UI != UE; ++UI) {
13465 if (UI->getOpcode() == ISD::ADD &&
13466 isa<ConstantSDNode>(UI->getOperand(1)) &&
13467 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
13468 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
13469 (1ULL << Bits) == 0) {
13470 SDNode *OtherAdd = *UI;
13471 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
13472 VE = OtherAdd->use_end(); VI != VE; ++VI) {
13473 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13474 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
13475 return SDValue(*VI, 0);
13476 }
13477 }
13478 }
13479 }
13480 }
13481 }
13482
13483 // Combine vmaxsw/h/b(a, a's negation) to abs(a)
13484 // Expose the vabsduw/h/b opportunity for down stream
13485 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
13486 (IID == Intrinsic::ppc_altivec_vmaxsw ||
13487 IID == Intrinsic::ppc_altivec_vmaxsh ||
13488 IID == Intrinsic::ppc_altivec_vmaxsb)) {
13489 SDValue V1 = N->getOperand(1);
13490 SDValue V2 = N->getOperand(2);
13491 if ((V1.getSimpleValueType() == MVT::v4i32 ||
13492 V1.getSimpleValueType() == MVT::v8i16 ||
13493 V1.getSimpleValueType() == MVT::v16i8) &&
13494 V1.getSimpleValueType() == V2.getSimpleValueType()) {
13495 // (0-a, a)
13496 if (V1.getOpcode() == ISD::SUB &&
13497 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
13498 V1.getOperand(1) == V2) {
13499 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
13500 }
13501 // (a, 0-a)
13502 if (V2.getOpcode() == ISD::SUB &&
13503 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
13504 V2.getOperand(1) == V1) {
13505 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13506 }
13507 // (x-y, y-x)
13508 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
13509 V1.getOperand(0) == V2.getOperand(1) &&
13510 V1.getOperand(1) == V2.getOperand(0)) {
13511 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
13512 }
13513 }
13514 }
13515 }
13516
13517 break;
13518 case ISD::INTRINSIC_W_CHAIN:
13519 // For little endian, VSX loads require generating lxvd2x/xxswapd.
13520 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13521 if (Subtarget.needsSwapsForVSXMemOps()) {
13522 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13523 default:
13524 break;
13525 case Intrinsic::ppc_vsx_lxvw4x:
13526 case Intrinsic::ppc_vsx_lxvd2x:
13527 return expandVSXLoadForLE(N, DCI);
13528 }
13529 }
13530 break;
13531 case ISD::INTRINSIC_VOID:
13532 // For little endian, VSX stores require generating xxswapd/stxvd2x.
13533 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13534 if (Subtarget.needsSwapsForVSXMemOps()) {
13535 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13536 default:
13537 break;
13538 case Intrinsic::ppc_vsx_stxvw4x:
13539 case Intrinsic::ppc_vsx_stxvd2x:
13540 return expandVSXStoreForLE(N, DCI);
13541 }
13542 }
13543 break;
13544 case ISD::BSWAP:
13545 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
13546 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
13547 N->getOperand(0).hasOneUse() &&
13548 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
13549 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
13550 N->getValueType(0) == MVT::i64))) {
13551 SDValue Load = N->getOperand(0);
13552 LoadSDNode *LD = cast<LoadSDNode>(Load);
13553 // Create the byte-swapping load.
13554 SDValue Ops[] = {
13555 LD->getChain(), // Chain
13556 LD->getBasePtr(), // Ptr
13557 DAG.getValueType(N->getValueType(0)) // VT
13558 };
13559 SDValue BSLoad =
13560 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
13561 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
13562 MVT::i64 : MVT::i32, MVT::Other),
13563 Ops, LD->getMemoryVT(), LD->getMemOperand());
13564
13565 // If this is an i16 load, insert the truncate.
13566 SDValue ResVal = BSLoad;
13567 if (N->getValueType(0) == MVT::i16)
13568 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
13569
13570 // First, combine the bswap away. This makes the value produced by the
13571 // load dead.
13572 DCI.CombineTo(N, ResVal);
13573
13574 // Next, combine the load away, we give it a bogus result value but a real
13575 // chain result. The result value is dead because the bswap is dead.
13576 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
13577
13578 // Return N so it doesn't get rechecked!
13579 return SDValue(N, 0);
13580 }
13581 break;
13582 case PPCISD::VCMP:
13583 // If a VCMPo node already exists with exactly the same operands as this
13584 // node, use its result instead of this node (VCMPo computes both a CR6 and
13585 // a normal output).
13586 //
13587 if (!N->getOperand(0).hasOneUse() &&
13588 !N->getOperand(1).hasOneUse() &&
13589 !N->getOperand(2).hasOneUse()) {
13590
13591 // Scan all of the users of the LHS, looking for VCMPo's that match.
13592 SDNode *VCMPoNode = nullptr;
13593
13594 SDNode *LHSN = N->getOperand(0).getNode();
13595 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
13596 UI != E; ++UI)
13597 if (UI->getOpcode() == PPCISD::VCMPo &&
13598 UI->getOperand(1) == N->getOperand(1) &&
13599 UI->getOperand(2) == N->getOperand(2) &&
13600 UI->getOperand(0) == N->getOperand(0)) {
13601 VCMPoNode = *UI;
13602 break;
13603 }
13604
13605 // If there is no VCMPo node, or if the flag value has a single use, don't
13606 // transform this.
13607 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
13608 break;
13609
13610 // Look at the (necessarily single) use of the flag value. If it has a
13611 // chain, this transformation is more complex. Note that multiple things
13612 // could use the value result, which we should ignore.
13613 SDNode *FlagUser = nullptr;
13614 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
13615 FlagUser == nullptr; ++UI) {
13616 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
13617 SDNode *User = *UI;
13618 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
13619 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
13620 FlagUser = User;
13621 break;
13622 }
13623 }
13624 }
13625
13626 // If the user is a MFOCRF instruction, we know this is safe.
13627 // Otherwise we give up for right now.
13628 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
13629 return SDValue(VCMPoNode, 0);
13630 }
13631 break;
13632 case ISD::BRCOND: {
13633 SDValue Cond = N->getOperand(1);
13634 SDValue Target = N->getOperand(2);
13635
13636 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13637 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
13638 Intrinsic::loop_decrement) {
13639
13640 // We now need to make the intrinsic dead (it cannot be instruction
13641 // selected).
13642 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
13643 assert(Cond.getNode()->hasOneUse() &&
13644 "Counter decrement has more than one use");
13645
13646 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
13647 N->getOperand(0), Target);
13648 }
13649 }
13650 break;
13651 case ISD::BR_CC: {
13652 // If this is a branch on an altivec predicate comparison, lower this so
13653 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
13654 // lowering is done pre-legalize, because the legalizer lowers the predicate
13655 // compare down to code that is difficult to reassemble.
13656 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13657 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
13658
13659 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
13660 // value. If so, pass-through the AND to get to the intrinsic.
13661 if (LHS.getOpcode() == ISD::AND &&
13662 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13663 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
13664 Intrinsic::loop_decrement &&
13665 isa<ConstantSDNode>(LHS.getOperand(1)) &&
13666 !isNullConstant(LHS.getOperand(1)))
13667 LHS = LHS.getOperand(0);
13668
13669 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
13670 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
13671 Intrinsic::loop_decrement &&
13672 isa<ConstantSDNode>(RHS)) {
13673 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
13674 "Counter decrement comparison is not EQ or NE");
13675
13676 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13677 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
13678 (CC == ISD::SETNE && !Val);
13679
13680 // We now need to make the intrinsic dead (it cannot be instruction
13681 // selected).
13682 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
13683 assert(LHS.getNode()->hasOneUse() &&
13684 "Counter decrement has more than one use");
13685
13686 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
13687 N->getOperand(0), N->getOperand(4));
13688 }
13689
13690 int CompareOpc;
13691 bool isDot;
13692
13693 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13694 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
13695 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
13696 assert(isDot && "Can't compare against a vector result!");
13697
13698 // If this is a comparison against something other than 0/1, then we know
13699 // that the condition is never/always true.
13700 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
13701 if (Val != 0 && Val != 1) {
13702 if (CC == ISD::SETEQ) // Cond never true, remove branch.
13703 return N->getOperand(0);
13704 // Always !=, turn it into an unconditional branch.
13705 return DAG.getNode(ISD::BR, dl, MVT::Other,
13706 N->getOperand(0), N->getOperand(4));
13707 }
13708
13709 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
13710
13711 // Create the PPCISD altivec 'dot' comparison node.
13712 SDValue Ops[] = {
13713 LHS.getOperand(2), // LHS of compare
13714 LHS.getOperand(3), // RHS of compare
13715 DAG.getConstant(CompareOpc, dl, MVT::i32)
13716 };
13717 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
13718 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
13719
13720 // Unpack the result based on how the target uses it.
13721 PPC::Predicate CompOpc;
13722 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
13723 default: // Can't happen, don't crash on invalid number though.
13724 case 0: // Branch on the value of the EQ bit of CR6.
13725 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
13726 break;
13727 case 1: // Branch on the inverted value of the EQ bit of CR6.
13728 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
13729 break;
13730 case 2: // Branch on the value of the LT bit of CR6.
13731 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
13732 break;
13733 case 3: // Branch on the inverted value of the LT bit of CR6.
13734 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
13735 break;
13736 }
13737
13738 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
13739 DAG.getConstant(CompOpc, dl, MVT::i32),
13740 DAG.getRegister(PPC::CR6, MVT::i32),
13741 N->getOperand(4), CompNode.getValue(1));
13742 }
13743 break;
13744 }
13745 case ISD::BUILD_VECTOR:
13746 return DAGCombineBuildVector(N, DCI);
13747 case ISD::ABS:
13748 return combineABS(N, DCI);
13749 case ISD::VSELECT:
13750 return combineVSelect(N, DCI);
13751 }
13752
13753 return SDValue();
13754}
13755
13756SDValue
13757PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
13758 SelectionDAG &DAG,
13759 SmallVectorImpl<SDNode *> &Created) const {
13760 // fold (sdiv X, pow2)
13761 EVT VT = N->getValueType(0);
13762 if (VT == MVT::i64 && !Subtarget.isPPC64())
13763 return SDValue();
13764 if ((VT != MVT::i32 && VT != MVT::i64) ||
13765 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
13766 return SDValue();
13767
13768 SDLoc DL(N);
13769 SDValue N0 = N->getOperand(0);
13770
13771 bool IsNegPow2 = (-Divisor).isPowerOf2();
13772 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
13773 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
13774
13775 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
13776 Created.push_back(Op.getNode());
13777
13778 if (IsNegPow2) {
13779 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
13780 Created.push_back(Op.getNode());
13781 }
13782
13783 return Op;
13784}
13785
13786//===----------------------------------------------------------------------===//
13787// Inline Assembly Support
13788//===----------------------------------------------------------------------===//
13789
13790void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13791 KnownBits &Known,
13792 const APInt &DemandedElts,
13793 const SelectionDAG &DAG,
13794 unsigned Depth) const {
13795 Known.resetAll();
13796 switch (Op.getOpcode()) {
13797 default: break;
13798 case PPCISD::LBRX: {
13799 // lhbrx is known to have the top bits cleared out.
13800 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
13801 Known.Zero = 0xFFFF0000;
13802 break;
13803 }
13804 case ISD::INTRINSIC_WO_CHAIN: {
13805 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
13806 default: break;
13807 case Intrinsic::ppc_altivec_vcmpbfp_p:
13808 case Intrinsic::ppc_altivec_vcmpeqfp_p:
13809 case Intrinsic::ppc_altivec_vcmpequb_p:
13810 case Intrinsic::ppc_altivec_vcmpequh_p:
13811 case Intrinsic::ppc_altivec_vcmpequw_p:
13812 case Intrinsic::ppc_altivec_vcmpequd_p:
13813 case Intrinsic::ppc_altivec_vcmpgefp_p:
13814 case Intrinsic::ppc_altivec_vcmpgtfp_p:
13815 case Intrinsic::ppc_altivec_vcmpgtsb_p:
13816 case Intrinsic::ppc_altivec_vcmpgtsh_p:
13817 case Intrinsic::ppc_altivec_vcmpgtsw_p:
13818 case Intrinsic::ppc_altivec_vcmpgtsd_p:
13819 case Intrinsic::ppc_altivec_vcmpgtub_p:
13820 case Intrinsic::ppc_altivec_vcmpgtuh_p:
13821 case Intrinsic::ppc_altivec_vcmpgtuw_p:
13822 case Intrinsic::ppc_altivec_vcmpgtud_p:
13823 Known.Zero = ~1U; // All bits but the low one are known to be zero.
13824 break;
13825 }
13826 }
13827 }
13828}
13829
13830unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
13831 switch (Subtarget.getDarwinDirective()) {
13832 default: break;
13833 case PPC::DIR_970:
13834 case PPC::DIR_PWR4:
13835 case PPC::DIR_PWR5:
13836 case PPC::DIR_PWR5X:
13837 case PPC::DIR_PWR6:
13838 case PPC::DIR_PWR6X:
13839 case PPC::DIR_PWR7:
13840 case PPC::DIR_PWR8:
13841 case PPC::DIR_PWR9: {
13842 if (!ML)
13843 break;
13844
13845 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13846
13847 // For small loops (between 5 and 8 instructions), align to a 32-byte
13848 // boundary so that the entire loop fits in one instruction-cache line.
13849 uint64_t LoopSize = 0;
13850 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
13851 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
13852 LoopSize += TII->getInstSizeInBytes(*J);
13853 if (LoopSize > 32)
13854 break;
13855 }
13856
13857 if (LoopSize > 16 && LoopSize <= 32)
13858 return 5;
13859
13860 break;
13861 }
13862 }
13863
13864 return TargetLowering::getPrefLoopAlignment(ML);
13865}
13866
13867/// getConstraintType - Given a constraint, return the type of
13868/// constraint it is for this target.
13869PPCTargetLowering::ConstraintType
13870PPCTargetLowering::getConstraintType(StringRef Constraint) const {
13871 if (Constraint.size() == 1) {
13872 switch (Constraint[0]) {
13873 default: break;
13874 case 'b':
13875 case 'r':
13876 case 'f':
13877 case 'd':
13878 case 'v':
13879 case 'y':
13880 return C_RegisterClass;
13881 case 'Z':
13882 // FIXME: While Z does indicate a memory constraint, it specifically
13883 // indicates an r+r address (used in conjunction with the 'y' modifier
13884 // in the replacement string). Currently, we're forcing the base
13885 // register to be r0 in the asm printer (which is interpreted as zero)
13886 // and forming the complete address in the second register. This is
13887 // suboptimal.
13888 return C_Memory;
13889 }
13890 } else if (Constraint == "wc") { // individual CR bits.
13891 return C_RegisterClass;
13892 } else if (Constraint == "wa" || Constraint == "wd" ||
13893 Constraint == "wf" || Constraint == "ws" ||
13894 Constraint == "wi") {
13895 return C_RegisterClass; // VSX registers.
13896 }
13897 return TargetLowering::getConstraintType(Constraint);
13898}
13899
13900/// Examine constraint type and operand type and determine a weight value.
13901/// This object must already have been set up with the operand type
13902/// and the current alternative constraint selected.
13903TargetLowering::ConstraintWeight
13904PPCTargetLowering::getSingleConstraintMatchWeight(
13905 AsmOperandInfo &info, const char *constraint) const {
13906 ConstraintWeight weight = CW_Invalid;
13907 Value *CallOperandVal = info.CallOperandVal;
13908 // If we don't have a value, we can't do a match,
13909 // but allow it at the lowest weight.
13910 if (!CallOperandVal)
13911 return CW_Default;
13912 Type *type = CallOperandVal->getType();
13913
13914 // Look at the constraint type.
13915 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
13916 return CW_Register; // an individual CR bit.
13917 else if ((StringRef(constraint) == "wa" ||
13918 StringRef(constraint) == "wd" ||
13919 StringRef(constraint) == "wf") &&
13920 type->isVectorTy())
13921 return CW_Register;
13922 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
13923 return CW_Register;
13924 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
13925 return CW_Register; // just hold 64-bit integers data.
13926
13927 switch (*constraint) {
13928 default:
13929 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13930 break;
13931 case 'b':
13932 if (type->isIntegerTy())
13933 weight = CW_Register;
13934 break;
13935 case 'f':
13936 if (type->isFloatTy())
13937 weight = CW_Register;
13938 break;
13939 case 'd':
13940 if (type->isDoubleTy())
13941 weight = CW_Register;
13942 break;
13943 case 'v':
13944 if (type->isVectorTy())
13945 weight = CW_Register;
13946 break;
13947 case 'y':
13948 weight = CW_Register;
13949 break;
13950 case 'Z':
13951 weight = CW_Memory;
13952 break;
13953 }
13954 return weight;
13955}
13956
13957std::pair<unsigned, const TargetRegisterClass *>
13958PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
13959 StringRef Constraint,
13960 MVT VT) const {
13961 if (Constraint.size() == 1) {
13962 // GCC RS6000 Constraint Letters
13963 switch (Constraint[0]) {
13964 case 'b': // R1-R31
13965 if (VT == MVT::i64 && Subtarget.isPPC64())
13966 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
13967 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
13968 case 'r': // R0-R31
13969 if (VT == MVT::i64 && Subtarget.isPPC64())
13970 return std::make_pair(0U, &PPC::G8RCRegClass);
13971 return std::make_pair(0U, &PPC::GPRCRegClass);
13972 // 'd' and 'f' constraints are both defined to be "the floating point
13973 // registers", where one is for 32-bit and the other for 64-bit. We don't
13974 // really care overly much here so just give them all the same reg classes.
13975 case 'd':
13976 case 'f':
13977 if (Subtarget.hasSPE()) {
13978 if (VT == MVT::f32 || VT == MVT::i32)
13979 return std::make_pair(0U, &PPC::SPE4RCRegClass);
13980 if (VT == MVT::f64 || VT == MVT::i64)
13981 return std::make_pair(0U, &PPC::SPERCRegClass);
13982 } else {
13983 if (VT == MVT::f32 || VT == MVT::i32)
13984 return std::make_pair(0U, &PPC::F4RCRegClass);
13985 if (VT == MVT::f64 || VT == MVT::i64)
13986 return std::make_pair(0U, &PPC::F8RCRegClass);
13987 if (VT == MVT::v4f64 && Subtarget.hasQPX())
13988 return std::make_pair(0U, &PPC::QFRCRegClass);
13989 if (VT == MVT::v4f32 && Subtarget.hasQPX())
13990 return std::make_pair(0U, &PPC::QSRCRegClass);
13991 }
13992 break;
13993 case 'v':
13994 if (VT == MVT::v4f64 && Subtarget.hasQPX())
13995 return std::make_pair(0U, &PPC::QFRCRegClass);
13996 if (VT == MVT::v4f32 && Subtarget.hasQPX())
13997 return std::make_pair(0U, &PPC::QSRCRegClass);
13998 if (Subtarget.hasAltivec())
13999 return std::make_pair(0U, &PPC::VRRCRegClass);
14000 break;
14001 case 'y': // crrc
14002 return std::make_pair(0U, &PPC::CRRCRegClass);
14003 }
14004 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14005 // An individual CR bit.
14006 return std::make_pair(0U, &PPC::CRBITRCRegClass);
14007 } else if ((Constraint == "wa" || Constraint == "wd" ||
14008 Constraint == "wf" || Constraint == "wi") &&
14009 Subtarget.hasVSX()) {
14010 return std::make_pair(0U, &PPC::VSRCRegClass);
14011 } else if (Constraint == "ws" && Subtarget.hasVSX()) {
14012 if (VT == MVT::f32 && Subtarget.hasP8Vector())
14013 return std::make_pair(0U, &PPC::VSSRCRegClass);
14014 else
14015 return std::make_pair(0U, &PPC::VSFRCRegClass);
14016 }
14017
14018 std::pair<unsigned, const TargetRegisterClass *> R =
14019 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14020
14021 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14022 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14023 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14024 // register.
14025 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14026 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14027 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14028 PPC::GPRCRegClass.contains(R.first))
14029 return std::make_pair(TRI->getMatchingSuperReg(R.first,
14030 PPC::sub_32, &PPC::G8RCRegClass),
14031 &PPC::G8RCRegClass);
14032
14033 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14034 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14035 R.first = PPC::CR0;
14036 R.second = &PPC::CRRCRegClass;
14037 }
14038
14039 return R;
14040}
14041
14042/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14043/// vector. If it is invalid, don't add anything to Ops.
14044void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14045 std::string &Constraint,
14046 std::vector<SDValue>&Ops,
14047 SelectionDAG &DAG) const {
14048 SDValue Result;
14049
14050 // Only support length 1 constraints.
14051 if (Constraint.length() > 1) return;
14052
14053 char Letter = Constraint[0];
14054 switch (Letter) {
14055 default: break;
14056 case 'I':
14057 case 'J':
14058 case 'K':
14059 case 'L':
14060 case 'M':
14061 case 'N':
14062 case 'O':
14063 case 'P': {
14064 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14065 if (!CST) return; // Must be an immediate to match.
14066 SDLoc dl(Op);
14067 int64_t Value = CST->getSExtValue();
14068 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14069 // numbers are printed as such.
14070 switch (Letter) {
14071 default: llvm_unreachable("Unknown constraint letter!");
14072 case 'I': // "I" is a signed 16-bit constant.
14073 if (isInt<16>(Value))
14074 Result = DAG.getTargetConstant(Value, dl, TCVT);
14075 break;
14076 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
14077 if (isShiftedUInt<16, 16>(Value))
14078 Result = DAG.getTargetConstant(Value, dl, TCVT);
14079 break;
14080 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
14081 if (isShiftedInt<16, 16>(Value))
14082 Result = DAG.getTargetConstant(Value, dl, TCVT);
14083 break;
14084 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
14085 if (isUInt<16>(Value))
14086 Result = DAG.getTargetConstant(Value, dl, TCVT);
14087 break;
14088 case 'M': // "M" is a constant that is greater than 31.
14089 if (Value > 31)
14090 Result = DAG.getTargetConstant(Value, dl, TCVT);
14091 break;
14092 case 'N': // "N" is a positive constant that is an exact power of two.
14093 if (Value > 0 && isPowerOf2_64(Value))
14094 Result = DAG.getTargetConstant(Value, dl, TCVT);
14095 break;
14096 case 'O': // "O" is the constant zero.
14097 if (Value == 0)
14098 Result = DAG.getTargetConstant(Value, dl, TCVT);
14099 break;
14100 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
14101 if (isInt<16>(-Value))
14102 Result = DAG.getTargetConstant(Value, dl, TCVT);
14103 break;
14104 }
14105 break;
14106 }
14107 }
14108
14109 if (Result.getNode()) {
14110 Ops.push_back(Result);
14111 return;
14112 }
14113
14114 // Handle standard constraint letters.
14115 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14116}
14117
14118// isLegalAddressingMode - Return true if the addressing mode represented
14119// by AM is legal for this target, for a load/store of the specified type.
14120bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14121 const AddrMode &AM, Type *Ty,
14122 unsigned AS, Instruction *I) const {
14123 // PPC does not allow r+i addressing modes for vectors!
14124 if (Ty->isVectorTy() && AM.BaseOffs != 0)
14125 return false;
14126
14127 // PPC allows a sign-extended 16-bit immediate field.
14128 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14129 return false;
14130
14131 // No global is ever allowed as a base.
14132 if (AM.BaseGV)
14133 return false;
14134
14135 // PPC only support r+r,
14136 switch (AM.Scale) {
14137 case 0: // "r+i" or just "i", depending on HasBaseReg.
14138 break;
14139 case 1:
14140 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
14141 return false;
14142 // Otherwise we have r+r or r+i.
14143 break;
14144 case 2:
14145 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
14146 return false;
14147 // Allow 2*r as r+r.
14148 break;
14149 default:
14150 // No other scales are supported.
14151 return false;
14152 }
14153
14154 return true;
14155}
14156
14157SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14158 SelectionDAG &DAG) const {
14159 MachineFunction &MF = DAG.getMachineFunction();
14160 MachineFrameInfo &MFI = MF.getFrameInfo();
14161 MFI.setReturnAddressIsTaken(true);
14162
14163 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14164 return SDValue();
14165
14166 SDLoc dl(Op);
14167 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14168
14169 // Make sure the function does not optimize away the store of the RA to
14170 // the stack.
14171 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14172 FuncInfo->setLRStoreRequired();
14173 bool isPPC64 = Subtarget.isPPC64();
14174 auto PtrVT = getPointerTy(MF.getDataLayout());
14175
14176 if (Depth > 0) {
14177 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14178 SDValue Offset =
14179 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14180 isPPC64 ? MVT::i64 : MVT::i32);
14181 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14182 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14183 MachinePointerInfo());
14184 }
14185
14186 // Just load the return address off the stack.
14187 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14188 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14189 MachinePointerInfo());
14190}
14191
14192SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14193 SelectionDAG &DAG) const {
14194 SDLoc dl(Op);
14195 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14196
14197 MachineFunction &MF = DAG.getMachineFunction();
14198 MachineFrameInfo &MFI = MF.getFrameInfo();
14199 MFI.setFrameAddressIsTaken(true);
14200
14201 EVT PtrVT = getPointerTy(MF.getDataLayout());
14202 bool isPPC64 = PtrVT == MVT::i64;
14203
14204 // Naked functions never have a frame pointer, and so we use r1. For all
14205 // other functions, this decision must be delayed until during PEI.
14206 unsigned FrameReg;
14207 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14208 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14209 else
14210 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14211
14212 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14213 PtrVT);
14214 while (Depth--)
14215 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14216 FrameAddr, MachinePointerInfo());
14217 return FrameAddr;
14218}
14219
14220// FIXME? Maybe this could be a TableGen attribute on some registers and
14221// this table could be generated automatically from RegInfo.
14222unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
14223 SelectionDAG &DAG) const {
14224 bool isPPC64 = Subtarget.isPPC64();
14225 bool isDarwinABI = Subtarget.isDarwinABI();
14226
14227 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
14228 (!isPPC64 && VT != MVT::i32))
14229 report_fatal_error("Invalid register global variable type");
14230
14231 bool is64Bit = isPPC64 && VT == MVT::i64;
14232 unsigned Reg = StringSwitch<unsigned>(RegName)
14233 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14234 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
14235 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
14236 (is64Bit ? PPC::X13 : PPC::R13))
14237 .Default(0);
14238
14239 if (Reg)
14240 return Reg;
14241 report_fatal_error("Invalid register name global variable");
14242}
14243
14244bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14245 // 32-bit SVR4 ABI access everything as got-indirect.
14246 if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
14247 return true;
14248
14249 CodeModel::Model CModel = getTargetMachine().getCodeModel();
14250 // If it is small or large code model, module locals are accessed
14251 // indirectly by loading their address from .toc/.got. The difference
14252 // is that for large code model we have ADDISTocHa + LDtocL and for
14253 // small code model we simply have LDtoc.
14254 if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14255 return true;
14256
14257 // JumpTable and BlockAddress are accessed as got-indirect.
14258 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14259 return true;
14260
14261 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
14262 const GlobalValue *GV = G->getGlobal();
14263 unsigned char GVFlags = Subtarget.classifyGlobalReference(GV);
14264 // The NLP flag indicates that a global access has to use an
14265 // extra indirection.
14266 if (GVFlags & PPCII::MO_NLP_FLAG)
14267 return true;
14268 }
14269
14270 return false;
14271}
14272
14273bool
14274PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14275 // The PowerPC target isn't yet aware of offsets.
14276 return false;
14277}
14278
14279bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14280 const CallInst &I,
14281 MachineFunction &MF,
14282 unsigned Intrinsic) const {
14283 switch (Intrinsic) {
14284 case Intrinsic::ppc_qpx_qvlfd:
14285 case Intrinsic::ppc_qpx_qvlfs:
14286 case Intrinsic::ppc_qpx_qvlfcd:
14287 case Intrinsic::ppc_qpx_qvlfcs:
14288 case Intrinsic::ppc_qpx_qvlfiwa:
14289 case Intrinsic::ppc_qpx_qvlfiwz:
14290 case Intrinsic::ppc_altivec_lvx:
14291 case Intrinsic::ppc_altivec_lvxl:
14292 case Intrinsic::ppc_altivec_lvebx:
14293 case Intrinsic::ppc_altivec_lvehx:
14294 case Intrinsic::ppc_altivec_lvewx:
14295 case Intrinsic::ppc_vsx_lxvd2x:
14296 case Intrinsic::ppc_vsx_lxvw4x: {
14297 EVT VT;
14298 switch (Intrinsic) {
14299 case Intrinsic::ppc_altivec_lvebx:
14300 VT = MVT::i8;
14301 break;
14302 case Intrinsic::ppc_altivec_lvehx:
14303 VT = MVT::i16;
14304 break;
14305 case Intrinsic::ppc_altivec_lvewx:
14306 VT = MVT::i32;
14307 break;
14308 case Intrinsic::ppc_vsx_lxvd2x:
14309 VT = MVT::v2f64;
14310 break;
14311 case Intrinsic::ppc_qpx_qvlfd:
14312 VT = MVT::v4f64;
14313 break;
14314 case Intrinsic::ppc_qpx_qvlfs:
14315 VT = MVT::v4f32;
14316 break;
14317 case Intrinsic::ppc_qpx_qvlfcd:
14318 VT = MVT::v2f64;
14319 break;
14320 case Intrinsic::ppc_qpx_qvlfcs:
14321 VT = MVT::v2f32;
14322 break;
14323 default:
14324 VT = MVT::v4i32;
14325 break;
14326 }
14327
14328 Info.opc = ISD::INTRINSIC_W_CHAIN;
14329 Info.memVT = VT;
14330 Info.ptrVal = I.getArgOperand(0);
14331 Info.offset = -VT.getStoreSize()+1;
14332 Info.size = 2*VT.getStoreSize()-1;
14333 Info.align = 1;
14334 Info.flags = MachineMemOperand::MOLoad;
14335 return true;
14336 }
14337 case Intrinsic::ppc_qpx_qvlfda:
14338 case Intrinsic::ppc_qpx_qvlfsa:
14339 case Intrinsic::ppc_qpx_qvlfcda:
14340 case Intrinsic::ppc_qpx_qvlfcsa:
14341 case Intrinsic::ppc_qpx_qvlfiwaa:
14342 case Intrinsic::ppc_qpx_qvlfiwza: {
14343 EVT VT;
14344 switch (Intrinsic) {
14345 case Intrinsic::ppc_qpx_qvlfda:
14346 VT = MVT::v4f64;
14347 break;
14348 case Intrinsic::ppc_qpx_qvlfsa:
14349 VT = MVT::v4f32;
14350 break;
14351 case Intrinsic::ppc_qpx_qvlfcda:
14352 VT = MVT::v2f64;
14353 break;
14354 case Intrinsic::ppc_qpx_qvlfcsa:
14355 VT = MVT::v2f32;
14356 break;
14357 default:
14358 VT = MVT::v4i32;
14359 break;
14360 }
14361
14362 Info.opc = ISD::INTRINSIC_W_CHAIN;
14363 Info.memVT = VT;
14364 Info.ptrVal = I.getArgOperand(0);
14365 Info.offset = 0;
14366 Info.size = VT.getStoreSize();
14367 Info.align = 1;
14368 Info.flags = MachineMemOperand::MOLoad;
14369 return true;
14370 }
14371 case Intrinsic::ppc_qpx_qvstfd:
14372 case Intrinsic::ppc_qpx_qvstfs:
14373 case Intrinsic::ppc_qpx_qvstfcd:
14374 case Intrinsic::ppc_qpx_qvstfcs:
14375 case Intrinsic::ppc_qpx_qvstfiw:
14376 case Intrinsic::ppc_altivec_stvx:
14377 case Intrinsic::ppc_altivec_stvxl:
14378 case Intrinsic::ppc_altivec_stvebx:
14379 case Intrinsic::ppc_altivec_stvehx:
14380 case Intrinsic::ppc_altivec_stvewx:
14381 case Intrinsic::ppc_vsx_stxvd2x:
14382 case Intrinsic::ppc_vsx_stxvw4x: {
14383 EVT VT;
14384 switch (Intrinsic) {
14385 case Intrinsic::ppc_altivec_stvebx:
14386 VT = MVT::i8;
14387 break;
14388 case Intrinsic::ppc_altivec_stvehx:
14389 VT = MVT::i16;
14390 break;
14391 case Intrinsic::ppc_altivec_stvewx:
14392 VT = MVT::i32;
14393 break;
14394 case Intrinsic::ppc_vsx_stxvd2x:
14395 VT = MVT::v2f64;
14396 break;
14397 case Intrinsic::ppc_qpx_qvstfd:
14398 VT = MVT::v4f64;
14399 break;
14400 case Intrinsic::ppc_qpx_qvstfs:
14401 VT = MVT::v4f32;
14402 break;
14403 case Intrinsic::ppc_qpx_qvstfcd:
14404 VT = MVT::v2f64;
14405 break;
14406 case Intrinsic::ppc_qpx_qvstfcs:
14407 VT = MVT::v2f32;
14408 break;
14409 default:
14410 VT = MVT::v4i32;
14411 break;
14412 }
14413
14414 Info.opc = ISD::INTRINSIC_VOID;
14415 Info.memVT = VT;
14416 Info.ptrVal = I.getArgOperand(1);
14417 Info.offset = -VT.getStoreSize()+1;
14418 Info.size = 2*VT.getStoreSize()-1;
14419 Info.align = 1;
14420 Info.flags = MachineMemOperand::MOStore;
14421 return true;
14422 }
14423 case Intrinsic::ppc_qpx_qvstfda:
14424 case Intrinsic::ppc_qpx_qvstfsa:
14425 case Intrinsic::ppc_qpx_qvstfcda:
14426 case Intrinsic::ppc_qpx_qvstfcsa:
14427 case Intrinsic::ppc_qpx_qvstfiwa: {
14428 EVT VT;
14429 switch (Intrinsic) {
14430 case Intrinsic::ppc_qpx_qvstfda:
14431 VT = MVT::v4f64;
14432 break;
14433 case Intrinsic::ppc_qpx_qvstfsa:
14434 VT = MVT::v4f32;
14435 break;
14436 case Intrinsic::ppc_qpx_qvstfcda:
14437 VT = MVT::v2f64;
14438 break;
14439 case Intrinsic::ppc_qpx_qvstfcsa:
14440 VT = MVT::v2f32;
14441 break;
14442 default:
14443 VT = MVT::v4i32;
14444 break;
14445 }
14446
14447 Info.opc = ISD::INTRINSIC_VOID;
14448 Info.memVT = VT;
14449 Info.ptrVal = I.getArgOperand(1);
14450 Info.offset = 0;
14451 Info.size = VT.getStoreSize();
14452 Info.align = 1;
14453 Info.flags = MachineMemOperand::MOStore;
14454 return true;
14455 }
14456 default:
14457 break;
14458 }
14459
14460 return false;
14461}
14462
14463/// getOptimalMemOpType - Returns the target specific optimal type for load
14464/// and store operations as a result of memset, memcpy, and memmove
14465/// lowering. If DstAlign is zero that means it's safe to destination
14466/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
14467/// means there isn't a need to check it against alignment requirement,
14468/// probably because the source does not need to be loaded. If 'IsMemset' is
14469/// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
14470/// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
14471/// source is constant so it does not need to be loaded.
14472/// It returns EVT::Other if the type should be determined using generic
14473/// target-independent logic.
14474EVT PPCTargetLowering::getOptimalMemOpType(
14475 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14476 bool ZeroMemset, bool MemcpyStrSrc,
14477 const AttributeList &FuncAttributes) const {
14478 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
14479 // When expanding a memset, require at least two QPX instructions to cover
14480 // the cost of loading the value to be stored from the constant pool.
14481 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
14482 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
14483 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14484 return MVT::v4f64;
14485 }
14486
14487 // We should use Altivec/VSX loads and stores when available. For unaligned
14488 // addresses, unaligned VSX loads are only fast starting with the P8.
14489 if (Subtarget.hasAltivec() && Size >= 16 &&
14490 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
14491 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
14492 return MVT::v4i32;
14493 }
14494
14495 if (Subtarget.isPPC64()) {
14496 return MVT::i64;
14497 }
14498
14499 return MVT::i32;
14500}
14501
14502/// Returns true if it is beneficial to convert a load of a constant
14503/// to just the constant itself.
14504bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14505 Type *Ty) const {
14506 assert(Ty->isIntegerTy());
14507
14508 unsigned BitSize = Ty->getPrimitiveSizeInBits();
14509 return !(BitSize == 0 || BitSize > 64);
14510}
14511
14512bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14513 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14514 return false;
14515 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14516 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14517 return NumBits1 == 64 && NumBits2 == 32;
14518}
14519
14520bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14521 if (!VT1.isInteger() || !VT2.isInteger())
14522 return false;
14523 unsigned NumBits1 = VT1.getSizeInBits();
14524 unsigned NumBits2 = VT2.getSizeInBits();
14525 return NumBits1 == 64 && NumBits2 == 32;
14526}
14527
14528bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14529 // Generally speaking, zexts are not free, but they are free when they can be
14530 // folded with other operations.
14531 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
14532 EVT MemVT = LD->getMemoryVT();
14533 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
14534 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
14535 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
14536 LD->getExtensionType() == ISD::ZEXTLOAD))
14537 return true;
14538 }
14539
14540 // FIXME: Add other cases...
14541 // - 32-bit shifts with a zext to i64
14542 // - zext after ctlz, bswap, etc.
14543 // - zext after and by a constant mask
14544
14545 return TargetLowering::isZExtFree(Val, VT2);
14546}
14547
14548bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
14549 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
14550 "invalid fpext types");
14551 // Extending to float128 is not free.
14552 if (DestVT == MVT::f128)
14553 return false;
14554 return true;
14555}
14556
14557bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14558 return isInt<16>(Imm) || isUInt<16>(Imm);
14559}
14560
14561bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14562 return isInt<16>(Imm) || isUInt<16>(Imm);
14563}
14564
14565bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
14566 unsigned,
14567 unsigned,
14568 MachineMemOperand::Flags,
14569 bool *Fast) const {
14570 if (DisablePPCUnaligned)
14571 return false;
14572
14573 // PowerPC supports unaligned memory access for simple non-vector types.
14574 // Although accessing unaligned addresses is not as efficient as accessing
14575 // aligned addresses, it is generally more efficient than manual expansion,
14576 // and generally only traps for software emulation when crossing page
14577 // boundaries.
14578
14579 if (!VT.isSimple())
14580 return false;
14581
14582 if (VT.getSimpleVT().isVector()) {
14583 if (Subtarget.hasVSX()) {
14584 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
14585 VT != MVT::v4f32 && VT != MVT::v4i32)
14586 return false;
14587 } else {
14588 return false;
14589 }
14590 }
14591
14592 if (VT == MVT::ppcf128)
14593 return false;
14594
14595 if (Fast)
14596 *Fast = true;
14597
14598 return true;
14599}
14600
14601bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14602 VT = VT.getScalarType();
14603
14604 if (!VT.isSimple())
14605 return false;
14606
14607 switch (VT.getSimpleVT().SimpleTy) {
14608 case MVT::f32:
14609 case MVT::f64:
14610 return true;
14611 case MVT::f128:
14612 return (EnableQuadPrecision && Subtarget.hasP9Vector());
14613 default:
14614 break;
14615 }
14616
14617 return false;
14618}
14619
14620const MCPhysReg *
14621PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
14622 // LR is a callee-save register, but we must treat it as clobbered by any call
14623 // site. Hence we include LR in the scratch registers, which are in turn added
14624 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
14625 // to CTR, which is used by any indirect call.
14626 static const MCPhysReg ScratchRegs[] = {
14627 PPC::X12, PPC::LR8, PPC::CTR8, 0
14628 };
14629
14630 return ScratchRegs;
14631}
14632
14633unsigned PPCTargetLowering::getExceptionPointerRegister(
14634 const Constant *PersonalityFn) const {
14635 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
14636}
14637
14638unsigned PPCTargetLowering::getExceptionSelectorRegister(
14639 const Constant *PersonalityFn) const {
14640 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
14641}
14642
14643bool
14644PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
14645 EVT VT , unsigned DefinedValues) const {
14646 if (VT == MVT::v2i64)
14647 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
14648
14649 if (Subtarget.hasVSX() || Subtarget.hasQPX())
14650 return true;
14651
14652 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
14653}
14654
14655Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
14656 if (DisableILPPref || Subtarget.enableMachineScheduler())
14657 return TargetLowering::getSchedulingPreference(N);
14658
14659 return Sched::ILP;
14660}
14661
14662// Create a fast isel object.
14663FastISel *
14664PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
14665 const TargetLibraryInfo *LibInfo) const {
14666 return PPC::createFastISel(FuncInfo, LibInfo);
14667}
14668
14669void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14670 if (Subtarget.isDarwinABI()) return;
14671 if (!Subtarget.isPPC64()) return;
14672
14673 // Update IsSplitCSR in PPCFunctionInfo
14674 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
14675 PFI->setIsSplitCSR(true);
14676}
14677
14678void PPCTargetLowering::insertCopiesSplitCSR(
14679 MachineBasicBlock *Entry,
14680 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14681 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
14682 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14683 if (!IStart)
14684 return;
14685
14686 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14687 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14688 MachineBasicBlock::iterator MBBI = Entry->begin();
14689 for (const MCPhysReg *I = IStart; *I; ++I) {
14690 const TargetRegisterClass *RC = nullptr;
14691 if (PPC::G8RCRegClass.contains(*I))
14692 RC = &PPC::G8RCRegClass;
14693 else if (PPC::F8RCRegClass.contains(*I))
14694 RC = &PPC::F8RCRegClass;
14695 else if (PPC::CRRCRegClass.contains(*I))
14696 RC = &PPC::CRRCRegClass;
14697 else if (PPC::VRRCRegClass.contains(*I))
14698 RC = &PPC::VRRCRegClass;
14699 else
14700 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14701
14702 unsigned NewVR = MRI->createVirtualRegister(RC);
14703 // Create copy from CSR to a virtual register.
14704 // FIXME: this currently does not emit CFI pseudo-instructions, it works
14705 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14706 // nounwind. If we want to generalize this later, we may need to emit
14707 // CFI pseudo-instructions.
14708 assert(Entry->getParent()->getFunction().hasFnAttribute(
14709 Attribute::NoUnwind) &&
14710 "Function should be nounwind in insertCopiesSplitCSR!");
14711 Entry->addLiveIn(*I);
14712 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14713 .addReg(*I);
14714
14715 // Insert the copy-back instructions right before the terminator.
14716 for (auto *Exit : Exits)
14717 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14718 TII->get(TargetOpcode::COPY), *I)
14719 .addReg(NewVR);
14720 }
14721}
14722
14723// Override to enable LOAD_STACK_GUARD lowering on Linux.
14724bool PPCTargetLowering::useLoadStackGuardNode() const {
14725 if (!Subtarget.isTargetLinux())
14726 return TargetLowering::useLoadStackGuardNode();
14727 return true;
14728}
14729
14730// Override to disable global variable loading on Linux.
14731void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
14732 if (!Subtarget.isTargetLinux())
14733 return TargetLowering::insertSSPDeclarations(M);
14734}
14735
14736bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
14737 bool ForCodeSize) const {
14738 if (!VT.isSimple() || !Subtarget.hasVSX())
14739 return false;
14740
14741 switch(VT.getSimpleVT().SimpleTy) {
14742 default:
14743 // For FP types that are currently not supported by PPC backend, return
14744 // false. Examples: f16, f80.
14745 return false;
14746 case MVT::f32:
14747 case MVT::f64:
14748 case MVT::ppcf128:
14749 return Imm.isPosZero();
14750 }
14751}
14752
14753// For vector shift operation op, fold
14754// (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
14755static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
14756 SelectionDAG &DAG) {
14757 SDValue N0 = N->getOperand(0);
14758 SDValue N1 = N->getOperand(1);
14759 EVT VT = N0.getValueType();
14760 unsigned OpSizeInBits = VT.getScalarSizeInBits();
14761 unsigned Opcode = N->getOpcode();
14762 unsigned TargetOpcode;
14763
14764 switch (Opcode) {
14765 default:
14766 llvm_unreachable("Unexpected shift operation");
14767 case ISD::SHL:
14768 TargetOpcode = PPCISD::SHL;
14769 break;
14770 case ISD::SRL:
14771 TargetOpcode = PPCISD::SRL;
14772 break;
14773 case ISD::SRA:
14774 TargetOpcode = PPCISD::SRA;
14775 break;
14776 }
14777
14778 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
14779 N1->getOpcode() == ISD::AND)
14780 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
14781 if (Mask->getZExtValue() == OpSizeInBits - 1)
14782 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
14783
14784 return SDValue();
14785}
14786
14787SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
14788 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14789 return Value;
14790
14791 SDValue N0 = N->getOperand(0);
14792 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
14793 if (!Subtarget.isISA3_0() ||
14794 N0.getOpcode() != ISD::SIGN_EXTEND ||
14795 N0.getOperand(0).getValueType() != MVT::i32 ||
14796 CN1 == nullptr || N->getValueType(0) != MVT::i64)
14797 return SDValue();
14798
14799 // We can't save an operation here if the value is already extended, and
14800 // the existing shift is easier to combine.
14801 SDValue ExtsSrc = N0.getOperand(0);
14802 if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
14803 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
14804 return SDValue();
14805
14806 SDLoc DL(N0);
14807 SDValue ShiftBy = SDValue(CN1, 0);
14808 // We want the shift amount to be i32 on the extswli, but the shift could
14809 // have an i64.
14810 if (ShiftBy.getValueType() == MVT::i64)
14811 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
14812
14813 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
14814 ShiftBy);
14815}
14816
14817SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
14818 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14819 return Value;
14820
14821 return SDValue();
14822}
14823
14824SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
14825 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
14826 return Value;
14827
14828 return SDValue();
14829}
14830
14831// Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
14832// Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
14833// When C is zero, the equation (addi Z, -C) can be simplified to Z
14834// Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
14835static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
14836 const PPCSubtarget &Subtarget) {
14837 if (!Subtarget.isPPC64())
14838 return SDValue();
14839
14840 SDValue LHS = N->getOperand(0);
14841 SDValue RHS = N->getOperand(1);
14842
14843 auto isZextOfCompareWithConstant = [](SDValue Op) {
14844 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
14845 Op.getValueType() != MVT::i64)
14846 return false;
14847
14848 SDValue Cmp = Op.getOperand(0);
14849 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
14850 Cmp.getOperand(0).getValueType() != MVT::i64)
14851 return false;
14852
14853 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
14854 int64_t NegConstant = 0 - Constant->getSExtValue();
14855 // Due to the limitations of the addi instruction,
14856 // -C is required to be [-32768, 32767].
14857 return isInt<16>(NegConstant);
14858 }
14859
14860 return false;
14861 };
14862
14863 bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
14864 bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
14865
14866 // If there is a pattern, canonicalize a zext operand to the RHS.
14867 if (LHSHasPattern && !RHSHasPattern)
14868 std::swap(LHS, RHS);
14869 else if (!LHSHasPattern && !RHSHasPattern)
14870 return SDValue();
14871
14872 SDLoc DL(N);
14873 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
14874 SDValue Cmp = RHS.getOperand(0);
14875 SDValue Z = Cmp.getOperand(0);
14876 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
14877
14878 assert(Constant && "Constant Should not be a null pointer.");
14879 int64_t NegConstant = 0 - Constant->getSExtValue();
14880
14881 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
14882 default: break;
14883 case ISD::SETNE: {
14884 // when C == 0
14885 // --> addze X, (addic Z, -1).carry
14886 // /
14887 // add X, (zext(setne Z, C))--
14888 // \ when -32768 <= -C <= 32767 && C != 0
14889 // --> addze X, (addic (addi Z, -C), -1).carry
14890 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
14891 DAG.getConstant(NegConstant, DL, MVT::i64));
14892 SDValue AddOrZ = NegConstant != 0 ? Add : Z;
14893 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
14894 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
14895 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
14896 SDValue(Addc.getNode(), 1));
14897 }
14898 case ISD::SETEQ: {
14899 // when C == 0
14900 // --> addze X, (subfic Z, 0).carry
14901 // /
14902 // add X, (zext(sete Z, C))--
14903 // \ when -32768 <= -C <= 32767 && C != 0
14904 // --> addze X, (subfic (addi Z, -C), 0).carry
14905 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
14906 DAG.getConstant(NegConstant, DL, MVT::i64));
14907 SDValue AddOrZ = NegConstant != 0 ? Add : Z;
14908 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
14909 DAG.getConstant(0, DL, MVT::i64), AddOrZ);
14910 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
14911 SDValue(Subc.getNode(), 1));
14912 }
14913 }
14914
14915 return SDValue();
14916}
14917
14918SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
14919 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
14920 return Value;
14921
14922 return SDValue();
14923}
14924
14925// Detect TRUNCATE operations on bitcasts of float128 values.
14926// What we are looking for here is the situtation where we extract a subset
14927// of bits from a 128 bit float.
14928// This can be of two forms:
14929// 1) BITCAST of f128 feeding TRUNCATE
14930// 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
14931// The reason this is required is because we do not have a legal i128 type
14932// and so we want to prevent having to store the f128 and then reload part
14933// of it.
14934SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
14935 DAGCombinerInfo &DCI) const {
14936 // If we are using CRBits then try that first.
14937 if (Subtarget.useCRBits()) {
14938 // Check if CRBits did anything and return that if it did.
14939 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
14940 return CRTruncValue;
14941 }
14942
14943 SDLoc dl(N);
14944 SDValue Op0 = N->getOperand(0);
14945
14946 // Looking for a truncate of i128 to i64.
14947 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
14948 return SDValue();
14949
14950 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
14951
14952 // SRL feeding TRUNCATE.
14953 if (Op0.getOpcode() == ISD::SRL) {
14954 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
14955 // The right shift has to be by 64 bits.
14956 if (!ConstNode || ConstNode->getZExtValue() != 64)
14957 return SDValue();
14958
14959 // Switch the element number to extract.
14960 EltToExtract = EltToExtract ? 0 : 1;
14961 // Update Op0 past the SRL.
14962 Op0 = Op0.getOperand(0);
14963 }
14964
14965 // BITCAST feeding a TRUNCATE possibly via SRL.
14966 if (Op0.getOpcode() == ISD::BITCAST &&
14967 Op0.getValueType() == MVT::i128 &&
14968 Op0.getOperand(0).getValueType() == MVT::f128) {
14969 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
14970 return DCI.DAG.getNode(
14971 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
14972 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
14973 }
14974 return SDValue();
14975}
14976
14977SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
14978 SelectionDAG &DAG = DCI.DAG;
14979
14980 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
14981 if (!ConstOpOrElement)
14982 return SDValue();
14983
14984 // An imul is usually smaller than the alternative sequence for legal type.
14985 if (DAG.getMachineFunction().getFunction().hasMinSize() &&
14986 isOperationLegal(ISD::MUL, N->getValueType(0)))
14987 return SDValue();
14988
14989 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
14990 switch (this->Subtarget.getDarwinDirective()) {
14991 default:
14992 // TODO: enhance the condition for subtarget before pwr8
14993 return false;
14994 case PPC::DIR_PWR8:
14995 // type mul add shl
14996 // scalar 4 1 1
14997 // vector 7 2 2
14998 return true;
14999 case PPC::DIR_PWR9:
15000 // type mul add shl
15001 // scalar 5 2 2
15002 // vector 7 2 2
15003
15004 // The cycle RATIO of related operations are showed as a table above.
15005 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15006 // scalar and vector type. For 2 instrs patterns, add/sub + shl
15007 // are 4, it is always profitable; but for 3 instrs patterns
15008 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15009 // So we should only do it for vector type.
15010 return IsAddOne && IsNeg ? VT.isVector() : true;
15011 }
15012 };
15013
15014 EVT VT = N->getValueType(0);
15015 SDLoc DL(N);
15016
15017 const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15018 bool IsNeg = MulAmt.isNegative();
15019 APInt MulAmtAbs = MulAmt.abs();
15020
15021 if ((MulAmtAbs - 1).isPowerOf2()) {
15022 // (mul x, 2^N + 1) => (add (shl x, N), x)
15023 // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15024
15025 if (!IsProfitable(IsNeg, true, VT))
15026 return SDValue();
15027
15028 SDValue Op0 = N->getOperand(0);
15029 SDValue Op1 =
15030 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15031 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15032 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15033
15034 if (!IsNeg)
15035 return Res;
15036
15037 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15038 } else if ((MulAmtAbs + 1).isPowerOf2()) {
15039 // (mul x, 2^N - 1) => (sub (shl x, N), x)
15040 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15041
15042 if (!IsProfitable(IsNeg, false, VT))
15043 return SDValue();
15044
15045 SDValue Op0 = N->getOperand(0);
15046 SDValue Op1 =
15047 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15048 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15049
15050 if (!IsNeg)
15051 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15052 else
15053 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15054
15055 } else {
15056 return SDValue();
15057 }
15058}
15059
15060bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15061 // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15062 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64())
15063 return false;
15064
15065 // If not a tail call then no need to proceed.
15066 if (!CI->isTailCall())
15067 return false;
15068
15069 // If tail calls are disabled for the caller then we are done.
15070 const Function *Caller = CI->getParent()->getParent();
15071 auto Attr = Caller->getFnAttribute("disable-tail-calls");
15072 if (Attr.getValueAsString() == "true")
15073 return false;
15074
15075 // If sibling calls have been disabled and tail-calls aren't guaranteed
15076 // there is no reason to duplicate.
15077 auto &TM = getTargetMachine();
15078 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15079 return false;
15080
15081 // Can't tail call a function called indirectly, or if it has variadic args.
15082 const Function *Callee = CI->getCalledFunction();
15083 if (!Callee || Callee->isVarArg())
15084 return false;
15085
15086 // Make sure the callee and caller calling conventions are eligible for tco.
15087 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15088 CI->getCallingConv()))
15089 return false;
15090
15091 // If the function is local then we have a good chance at tail-calling it
15092 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15093}
15094
15095bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15096 if (!Subtarget.hasVSX())
15097 return false;
15098 if (Subtarget.hasP9Vector() && VT == MVT::f128)
15099 return true;
15100 return VT == MVT::f32 || VT == MVT::f64 ||
15101 VT == MVT::v4f32 || VT == MVT::v2f64;
15102}
15103
15104bool PPCTargetLowering::
15105isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15106 const Value *Mask = AndI.getOperand(1);
15107 // If the mask is suitable for andi. or andis. we should sink the and.
15108 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15109 // Can't handle constants wider than 64-bits.
15110 if (CI->getBitWidth() > 64)
15111 return false;
15112 int64_t ConstVal = CI->getZExtValue();
15113 return isUInt<16>(ConstVal) ||
15114 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15115 }
15116
15117 // For non-constant masks, we can always use the record-form and.
15118 return true;
15119}
15120
15121// Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15122// Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15123// Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15124// Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15125// Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15126SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15127 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15128 assert(Subtarget.hasP9Altivec() &&
15129 "Only combine this when P9 altivec supported!");
15130 EVT VT = N->getValueType(0);
15131 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15132 return SDValue();
15133
15134 SelectionDAG &DAG = DCI.DAG;
15135 SDLoc dl(N);
15136 if (N->getOperand(0).getOpcode() == ISD::SUB) {
15137 // Even for signed integers, if it's known to be positive (as signed
15138 // integer) due to zero-extended inputs.
15139 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15140 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15141 if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15142 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15143 (SubOpcd1 == ISD::ZERO_EXTEND ||
15144 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15145 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15146 N->getOperand(0)->getOperand(0),
15147 N->getOperand(0)->getOperand(1),
15148 DAG.getTargetConstant(0, dl, MVT::i32));
15149 }
15150
15151 // For type v4i32, it can be optimized with xvnegsp + vabsduw
15152 if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15153 N->getOperand(0).hasOneUse()) {
15154 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15155 N->getOperand(0)->getOperand(0),
15156 N->getOperand(0)->getOperand(1),
15157 DAG.getTargetConstant(1, dl, MVT::i32));
15158 }
15159 }
15160
15161 return SDValue();
15162}
15163
15164// For type v4i32/v8ii16/v16i8, transform
15165// from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15166// from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15167// from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15168// from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15169SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15170 DAGCombinerInfo &DCI) const {
15171 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15172 assert(Subtarget.hasP9Altivec() &&
15173 "Only combine this when P9 altivec supported!");
15174
15175 SelectionDAG &DAG = DCI.DAG;
15176 SDLoc dl(N);
15177 SDValue Cond = N->getOperand(0);
15178 SDValue TrueOpnd = N->getOperand(1);
15179 SDValue FalseOpnd = N->getOperand(2);
15180 EVT VT = N->getOperand(1).getValueType();
15181
15182 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15183 FalseOpnd.getOpcode() != ISD::SUB)
15184 return SDValue();
15185
15186 // ABSD only available for type v4i32/v8i16/v16i8
15187 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15188 return SDValue();
15189
15190 // At least to save one more dependent computation
15191 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15192 return SDValue();
15193
15194 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15195
15196 // Can only handle unsigned comparison here
15197 switch (CC) {
15198 default:
15199 return SDValue();
15200 case ISD::SETUGT:
15201 case ISD::SETUGE:
15202 break;
15203 case ISD::SETULT:
15204 case ISD::SETULE:
15205 std::swap(TrueOpnd, FalseOpnd);
15206 break;
15207 }
15208
15209 SDValue CmpOpnd1 = Cond.getOperand(0);
15210 SDValue CmpOpnd2 = Cond.getOperand(1);
15211
15212 // SETCC CmpOpnd1 CmpOpnd2 cond
15213 // TrueOpnd = CmpOpnd1 - CmpOpnd2
15214 // FalseOpnd = CmpOpnd2 - CmpOpnd1
15215 if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15216 TrueOpnd.getOperand(1) == CmpOpnd2 &&
15217 FalseOpnd.getOperand(0) == CmpOpnd2 &&
15218 FalseOpnd.getOperand(1) == CmpOpnd1) {
15219 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15220 CmpOpnd1, CmpOpnd2,
15221 DAG.getTargetConstant(0, dl, MVT::i32));
15222 }
15223
15224 return SDValue();
15225}
15226